home.dart 12.5 KB
Newer Older
1
// Copyright 2018 The Chromium Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:async';
6 7 8
import 'dart:developer';
import 'dart:math' as math;

9 10
import 'package:flutter/material.dart';

11 12
import 'backdrop.dart';
import 'demos.dart';
13

14
const String _kGalleryAssetsPackage = 'flutter_gallery_assets';
15 16
const Color _kFlutterBlue = const Color(0xFF003D75);
const double _kDemoItemHeight = 64.0;
17
const Duration _kFrontLayerSwitchDuration = const Duration(milliseconds: 300);
18

19 20
class _FlutterLogo extends StatelessWidget {
  const _FlutterLogo({ Key key }) : super(key: key);
21

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
  @override
  Widget build(BuildContext context) {
    return new Center(
      child: new Container(
        width: 34.0,
        height: 34.0,
        decoration: const BoxDecoration(
          image: const DecorationImage(
            image: const AssetImage(
              'white_logo/logo.png',
              package: _kGalleryAssetsPackage,
            ),
          ),
        ),
      ),
    );
  }
}
40

41 42 43 44 45 46
class _CategoryItem extends StatelessWidget {
  const _CategoryItem({
    Key key,
    this.category,
    this.onTap,
  }) : super (key: key);
47

48 49
  final GalleryDemoCategory category;
  final VoidCallback onTap;
50 51 52

  @override
  Widget build(BuildContext context) {
53 54 55
    final ThemeData theme = Theme.of(context);
    final bool isDark = theme.brightness == Brightness.dark;

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    // This repaint boundary prevents the entire _CategoriesPage from being
    // repainted when the button's ink splash animates.
    return new RepaintBoundary(
      child: new RawMaterialButton(
        padding: EdgeInsets.zero,
        splashColor: theme.primaryColor.withOpacity(0.12),
        highlightColor: Colors.transparent,
        onPressed: onTap,
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            new Padding(
              padding: const EdgeInsets.all(6.0),
              child: new Icon(
                category.icon,
                size: 60.0,
73 74 75
                color: isDark ? Colors.white : _kFlutterBlue,
              ),
            ),
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
            const SizedBox(height: 10.0),
            new Container(
              height: 48.0,
              alignment: Alignment.center,
              child: new Text(
                category.name,
                textAlign: TextAlign.center,
                style: theme.textTheme.subhead.copyWith(
                  fontFamily: 'GoogleSans',
                  color: isDark ? Colors.white : _kFlutterBlue,
                ),
              ),
            ),
          ],
        ),
91
      ),
92 93 94 95
    );
  }
}

96 97
class _CategoriesPage extends StatelessWidget {
  const _CategoriesPage({
98
    Key key,
99 100 101
    this.categories,
    this.onCategoryTap,
  }) : super(key: key);
102

103 104 105 106 107 108 109 110 111
  final Iterable<GalleryDemoCategory> categories;
  final ValueChanged<GalleryDemoCategory> onCategoryTap;

  @override
  Widget build(BuildContext context) {
    const double aspectRatio = 160.0 / 180.0;
    final List<GalleryDemoCategory> categoriesList = categories.toList();
    final int columnCount = (MediaQuery.of(context).orientation == Orientation.portrait) ? 2 : 3;

112 113 114 115 116 117 118 119 120 121
    return new Semantics(
      scopesRoute: true,
      namesRoute: true,
      label: 'categories',
      explicitChildNodes: true,
      child: new SingleChildScrollView(
        key: const PageStorageKey<String>('categories'),
        child: new LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
            final double columnWidth = constraints.biggest.width / columnCount.toDouble();
122
            final double rowHeight = math.min(225.0, columnWidth * aspectRatio);
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
            final int rowCount = (categories.length + columnCount - 1) ~/ columnCount;

            // This repaint boundary prevents the inner contents of the front layer
            // from repainting when the backdrop toggle triggers a repaint on the
            // LayoutBuilder.
            return new RepaintBoundary(
              child: new Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: new List<Widget>.generate(rowCount, (int rowIndex) {
                  final int columnCountForRow = rowIndex == rowCount - 1
                    ? categories.length - columnCount * math.max(0, rowCount - 1)
                    : columnCount;

                  return new Row(
                    children: new List<Widget>.generate(columnCountForRow, (int columnIndex) {
                      final int index = rowIndex * columnCount + columnIndex;
                      final GalleryDemoCategory category = categoriesList[index];

                      return new SizedBox(
                        width: columnWidth,
                        height: rowHeight,
                        child: new _CategoryItem(
                          category: category,
                          onTap: () {
                            onCategoryTap(category);
                          },
                        ),
                      );
                    }),
                  );
                }),
              ),
            );
          },
        ),
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
      ),
    );
  }
}

class _DemoItem extends StatelessWidget {
  const _DemoItem({ Key key, this.demo }) : super(key: key);

  final GalleryDemo demo;

  void _launchDemo(BuildContext context) {
    if (demo.routeName != null) {
      Timeline.instantSync('Start Transition', arguments: <String, String>{
        'from': '/',
        'to': demo.routeName,
      });
      Navigator.pushNamed(context, demo.routeName);
    }
  }
178

179 180 181 182
  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    final bool isDark = theme.brightness == Brightness.dark;
183
    final double textScaleFactor = MediaQuery.textScaleFactorOf(context);
184

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    final List<Widget> titleChildren = <Widget>[
      new Text(
        demo.title,
        style: theme.textTheme.subhead.copyWith(
          color: isDark ? Colors.white : const Color(0xFF202124),
        ),
      ),
    ];
    if (demo.subtitle != null) {
      titleChildren.add(
        new Text(
          demo.subtitle,
          style: theme.textTheme.body1.copyWith(
            color: isDark ? Colors.white : const Color(0xFF60646B)
          ),
        ),
      );
    }

204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    return new RawMaterialButton(
      padding: EdgeInsets.zero,
      splashColor: theme.primaryColor.withOpacity(0.12),
      highlightColor: Colors.transparent,
      onPressed: () {
        _launchDemo(context);
      },
      child: new Container(
        constraints: new BoxConstraints(minHeight: _kDemoItemHeight * textScaleFactor),
        child: new Row(
          children: <Widget>[
            new Container(
              width: 56.0,
              height: 56.0,
              alignment: Alignment.center,
              child: new Icon(
                demo.icon,
                size: 24.0,
                color: isDark ? Colors.white : _kFlutterBlue,
              ),
            ),
            new Expanded(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
229
                children: titleChildren,
230 231 232 233 234 235 236 237 238
              ),
            ),
            const SizedBox(width: 44.0),
          ],
        ),
      ),
    );
  }
}
239

240 241
class _DemosPage extends StatelessWidget {
  const _DemosPage(this.category);
242

243
  final GalleryDemoCategory category;
Eric Seidel's avatar
Eric Seidel committed
244

245 246
  @override
  Widget build(BuildContext context) {
247 248
    return new KeyedSubtree(
      key: const ValueKey<String>('GalleryDemoList'), // So the tests can find this ListView
249 250 251 252 253 254 255 256 257 258 259 260
      child: new Semantics(
        scopesRoute: true,
        namesRoute: true,
        label: category.name,
        explicitChildNodes: true,
        child: new ListView(
          key: new PageStorageKey<String>(category.name),
          padding: const EdgeInsets.only(top: 8.0),
          children: kGalleryCategoryToDemos[category].map<Widget>((GalleryDemo demo) {
            return new _DemoItem(demo: demo);
          }).toList(),
        ),
261 262 263 264
      ),
    );
  }
}
265

266 267 268 269
class GalleryHome extends StatefulWidget {
  // In checked mode our MaterialApp will show the default "debug" banner.
  // Otherwise show the "preview" banner.
  static bool showPreviewBanner = true;
270

271 272
  const GalleryHome({
    Key key,
273
    this.testMode: false,
274 275
    this.optionsPage,
  }) : super(key: key);
276

277
  final Widget optionsPage;
278
  final bool testMode;
279

280
  @override
281
  _GalleryHomeState createState() => new _GalleryHomeState();
282 283
}

284
class _GalleryHomeState extends State<GalleryHome> with SingleTickerProviderStateMixin {
285
  static final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
286
  AnimationController _controller;
287
  GalleryDemoCategory _category;
288

289 290 291 292 293 294 295 296 297 298 299 300
  static Widget _topHomeLayout(Widget currentChild, List<Widget> previousChildren) {
    List<Widget> children = previousChildren;
    if (currentChild != null)
      children = children.toList()..add(currentChild);
    return new Stack(
      children: children,
      alignment: Alignment.topCenter,
    );
  }

  static const AnimatedSwitcherLayoutBuilder _centerHomeLayout = AnimatedSwitcher.defaultLayoutBuilder;

301 302 303
  @override
  void initState() {
    super.initState();
304 305 306 307 308
    _controller = new AnimationController(
      duration: const Duration(milliseconds: 600),
      debugLabel: 'preview banner',
      vsync: this,
    )..forward();
309 310 311 312 313 314 315 316
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

317 318
  @override
  Widget build(BuildContext context) {
319 320
    final ThemeData theme = Theme.of(context);
    final bool isDark = theme.brightness == Brightness.dark;
321 322
    final MediaQueryData media = MediaQuery.of(context);
    final bool centerHome = media.orientation == Orientation.portrait && media.size.height < 800.0;
323

324 325 326
    const Curve switchOutCurve = const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn);
    const Curve switchInCurve = const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn);

327
    Widget home = new Scaffold(
328
      key: _scaffoldKey,
329 330 331
      backgroundColor: isDark ? _kFlutterBlue : theme.primaryColor,
      body: new SafeArea(
        bottom: false,
332 333 334 335 336 337 338 339 340 341 342 343 344 345
        child: new WillPopScope(
          onWillPop: () {
            // Pop the category page if Android back button is pressed.
            if (_category != null) {
              setState(() => _category = null);
              return new Future<bool>.value(false);
            }
            return new Future<bool>.value(true);
          },
          child: new Backdrop(
            backTitle: const Text('Options'),
            backLayer: widget.optionsPage,
            frontAction: new AnimatedSwitcher(
              duration: _kFrontLayerSwitchDuration,
346 347
              switchOutCurve: switchOutCurve,
              switchInCurve: switchInCurve,
348 349 350 351 352 353 354 355
              child: _category == null
                ? const _FlutterLogo()
                : new IconButton(
                  icon: const BackButtonIcon(),
                  tooltip: 'Back',
                  onPressed: () => setState(() => _category = null),
                ),
            ),
356
            frontTitle: new AnimatedSwitcher(
357 358 359 360 361
              duration: _kFrontLayerSwitchDuration,
              child: _category == null
                ? const Text('Flutter gallery')
                : new Text(_category.name),
            ),
362
            frontHeading: widget.testMode ? null: new Container(height: 24.0),
363 364
            frontLayer: new AnimatedSwitcher(
              duration: _kFrontLayerSwitchDuration,
365 366
              switchOutCurve: switchOutCurve,
              switchInCurve: switchInCurve,
367
              layoutBuilder: centerHome ? _centerHomeLayout : _topHomeLayout,
368 369 370 371 372 373 374 375 376
              child: _category != null
                ? new _DemosPage(_category)
                : new _CategoriesPage(
                  categories: kAllGalleryDemoCategories,
                  onCategoryTap: (GalleryDemoCategory category) {
                    setState(() => _category = category);
                  },
                ),
            ),
377
          ),
378 379
        ),
      ),
380
    );
381 382

    assert(() {
383
      GalleryHome.showPreviewBanner = false;
384
      return true;
385
    }());
386

387
    if (GalleryHome.showPreviewBanner) {
388
      home = new Stack(
389
        fit: StackFit.expand,
390 391 392 393
        children: <Widget>[
          home,
          new FadeTransition(
            opacity: new CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
394
            child: const Banner(
395
              message: 'PREVIEW',
396
              location: BannerLocation.topEnd,
397 398 399 400 401 402 403
            )
          ),
        ]
      );
    }

    return home;
404 405
  }
}