home.dart 12.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter 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
import 'package:flutter/gestures.dart' show DragStartBehavior;
12

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

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

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

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

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

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

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

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

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

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

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

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

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

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

182 183 184 185
  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    final bool isDark = theme.brightness == Brightness.dark;
186
    final double textScaleFactor = MediaQuery.textScaleFactorOf(context);
187
    return RawMaterialButton(
188 189 190 191 192 193
      padding: EdgeInsets.zero,
      splashColor: theme.primaryColor.withOpacity(0.12),
      highlightColor: Colors.transparent,
      onPressed: () {
        _launchDemo(context);
      },
194 195 196
      child: Container(
        constraints: BoxConstraints(minHeight: _kDemoItemHeight * textScaleFactor),
        child: Row(
197
          children: <Widget>[
198
            Container(
199 200 201
              width: 56.0,
              height: 56.0,
              alignment: Alignment.center,
202
              child: Icon(
203 204 205 206 207
                demo.icon,
                size: 24.0,
                color: isDark ? Colors.white : _kFlutterBlue,
              ),
            ),
208 209
            Expanded(
              child: Column(
210 211
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
212 213 214
                children: <Widget>[
                  Text(
                    demo.title,
215
                    style: theme.textTheme.subtitle1.copyWith(
216 217 218 219 220 221
                      color: isDark ? Colors.white : const Color(0xFF202124),
                    ),
                  ),
                  if (demo.subtitle != null)
                    Text(
                      demo.subtitle,
222
                      style: theme.textTheme.bodyText2.copyWith(
223 224 225 226
                        color: isDark ? Colors.white : const Color(0xFF60646B)
                      ),
                    ),
                ],
227 228 229 230 231 232 233 234 235
              ),
            ),
            const SizedBox(width: 44.0),
          ],
        ),
      ),
    );
  }
}
236

237 238
class _DemosPage extends StatelessWidget {
  const _DemosPage(this.category);
239

240
  final GalleryDemoCategory category;
Eric Seidel's avatar
Eric Seidel committed
241

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

267 268 269
class GalleryHome extends StatefulWidget {
  const GalleryHome({
    Key key,
270
    this.testMode = false,
271 272
    this.optionsPage,
  }) : super(key: key);
273

274
  final Widget optionsPage;
275
  final bool testMode;
276

277 278 279 280
  // In checked mode our MaterialApp will show the default "debug" banner.
  // Otherwise show the "preview" banner.
  static bool showPreviewBanner = true;

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

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

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

  static const AnimatedSwitcherLayoutBuilder _centerHomeLayout = AnimatedSwitcher.defaultLayoutBuilder;

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

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

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

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

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

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

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

    return home;
409 410
  }
}