home.dart 12.7 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
import 'package:flutter/material.dart';
10
import 'package:flutter/services.dart';
11

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

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

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

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

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

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

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

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

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

104 105 106 107 108 109 110 111 112
  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;

113
    return Semantics(
114 115 116 117
      scopesRoute: true,
      namesRoute: true,
      label: 'categories',
      explicitChildNodes: true,
118
      child: SingleChildScrollView(
119
        key: const PageStorageKey<String>('categories'),
120
        child: LayoutBuilder(
121 122
          builder: (BuildContext context, BoxConstraints constraints) {
            final double columnWidth = constraints.biggest.width / columnCount.toDouble();
123
            final double rowHeight = math.min(225.0, columnWidth * aspectRatio);
124 125 126 127 128
            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.
129 130
            return RepaintBoundary(
              child: Column(
131 132
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
133
                children: List<Widget>.generate(rowCount, (int rowIndex) {
134 135 136 137
                  final int columnCountForRow = rowIndex == rowCount - 1
                    ? categories.length - columnCount * math.max(0, rowCount - 1)
                    : columnCount;

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

143
                      return SizedBox(
144 145
                        width: columnWidth,
                        height: rowHeight,
146
                        child: _CategoryItem(
147 148 149 150 151 152 153 154 155 156 157 158 159
                          category: category,
                          onTap: () {
                            onCategoryTap(category);
                          },
                        ),
                      );
                    }),
                  );
                }),
              ),
            );
          },
        ),
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
      ),
    );
  }
}

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);
    }
  }
179

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

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

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

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

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

246 247
  @override
  Widget build(BuildContext context) {
Jonah Williams's avatar
Jonah Williams committed
248
    // When overriding ListView.padding, it is necessary to manually handle
249 250
    // safe areas.
    final double windowBottomPadding = MediaQuery.of(context).padding.bottom;
251
    return KeyedSubtree(
252
      key: const ValueKey<String>('GalleryDemoList'), // So the tests can find this ListView
253
      child: Semantics(
254 255 256 257
        scopesRoute: true,
        namesRoute: true,
        label: category.name,
        explicitChildNodes: true,
258 259 260
        child: ListView(
          key: PageStorageKey<String>(category.name),
          padding: EdgeInsets.only(top: 8.0, bottom: windowBottomPadding),
261
          children: kGalleryCategoryToDemos[category].map<Widget>((GalleryDemo demo) {
262
            return _DemoItem(demo: demo);
263 264
          }).toList(),
        ),
265 266 267 268
      ),
    );
  }
}
269

270 271 272
class GalleryHome extends StatefulWidget {
  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 281 282 283
  // In checked mode our MaterialApp will show the default "debug" banner.
  // Otherwise show the "preview" banner.
  static bool showPreviewBanner = true;

284
  @override
285
  _GalleryHomeState createState() => _GalleryHomeState();
286 287
}

288
class _GalleryHomeState extends State<GalleryHome> with SingleTickerProviderStateMixin {
289
  static final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
290
  AnimationController _controller;
291
  GalleryDemoCategory _category;
292

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

  static const AnimatedSwitcherLayoutBuilder _centerHomeLayout = AnimatedSwitcher.defaultLayoutBuilder;

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

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

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

328 329
    const Curve switchOutCurve = Interval(0.4, 1.0, curve: Curves.fastOutSlowIn);
    const Curve switchInCurve = Interval(0.4, 1.0, curve: Curves.fastOutSlowIn);
330

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

    assert(() {
387
      GalleryHome.showPreviewBanner = false;
388
      return true;
389
    }());
390

391
    if (GalleryHome.showPreviewBanner) {
392
      home = Stack(
393
        fit: StackFit.expand,
394 395
        children: <Widget>[
          home,
396 397
          FadeTransition(
            opacity: CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
398
            child: const Banner(
399
              message: 'PREVIEW',
400
              location: BannerLocation.topEnd,
401 402 403 404 405
            )
          ),
        ]
      );
    }
406
    home = AnnotatedRegion<SystemUiOverlayStyle>(
407
      child: home,
408
      value: SystemUiOverlayStyle.light
409
    );
410 411

    return home;
412 413
  }
}