backdrop_demo.dart 11.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:math' as math;

import 'package:flutter/material.dart';

// This demo displays one Category at a time. The backdrop show a list
// of all of the categories and the selected category is displayed
// (CategoryView) on top of the backdrop.

class Category {
  const Category({ this.title, this.assets });
  final String title;
  final List<String> assets;
17 18
  @override
  String toString() => '$runtimeType("$title")';
19 20
}

21 22
const List<Category> allCategories = <Category>[
  Category(
23
    title: 'Accessories',
24
    assets: <String>[
25 26 27 28 29 30
      'products/belt.png',
      'products/earrings.png',
      'products/backpack.png',
      'products/hat.png',
      'products/scarf.png',
      'products/sunnies.png',
31 32
    ],
  ),
33
  Category(
34
    title: 'Blue',
35
    assets: <String>[
36 37 38 39
      'products/backpack.png',
      'products/cup.png',
      'products/napkins.png',
      'products/top.png',
40 41
    ],
  ),
42
  Category(
43
    title: 'Cold Weather',
44
    assets: <String>[
45 46 47 48 49
      'products/jacket.png',
      'products/jumper.png',
      'products/scarf.png',
      'products/sweater.png',
      'products/sweats.png',
50 51
    ],
  ),
52
  Category(
53
    title: 'Home',
54
    assets: <String>[
55 56 57 58 59
      'products/cup.png',
      'products/napkins.png',
      'products/planters.png',
      'products/table.png',
      'products/teaset.png',
60 61
    ],
  ),
62
  Category(
63
    title: 'Tops',
64
    assets: <String>[
65 66 67 68
      'products/jumper.png',
      'products/shirt.png',
      'products/sweater.png',
      'products/top.png',
69 70
    ],
  ),
71
  Category(
72
    title: 'Everything',
73
    assets: <String>[
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
      'products/backpack.png',
      'products/belt.png',
      'products/cup.png',
      'products/dress.png',
      'products/earrings.png',
      'products/flatwear.png',
      'products/hat.png',
      'products/jacket.png',
      'products/jumper.png',
      'products/napkins.png',
      'products/planters.png',
      'products/scarf.png',
      'products/shirt.png',
      'products/sunnies.png',
      'products/sweater.png',
      'products/sweats.png',
      'products/table.png',
      'products/teaset.png',
      'products/top.png',
93 94 95 96 97 98 99 100 101 102 103 104
    ],
  ),
];

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

  final Category category;

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
105 106
    return ListView(
      key: PageStorageKey<Category>(category),
107 108 109 110 111
      padding: const EdgeInsets.symmetric(
        vertical: 16.0,
        horizontal: 64.0,
      ),
      children: category.assets.map<Widget>((String asset) {
112
        return Column(
113 114
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
115 116
            Card(
              child: Container(
117 118
                width: 144.0,
                alignment: Alignment.center,
119
                child: Column(
120
                  children: <Widget>[
121
                    Image.asset(
122 123 124 125
                      asset,
                      package: 'flutter_gallery_assets',
                      fit: BoxFit.contain,
                    ),
126
                    Container(
127 128
                      padding: const EdgeInsets.only(bottom: 16.0),
                      alignment: AlignmentDirectional.center,
129
                      child: Text(
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 159 160 161 162 163 164 165 166
                        asset,
                        style: theme.textTheme.caption,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 24.0),
          ],
        );
      }).toList(),
    );
  }
}

// One BackdropPanel is visible at a time. It's stacked on top of the
// the BackdropDemo.
class BackdropPanel extends StatelessWidget {
  const BackdropPanel({
    Key key,
    this.onTap,
    this.onVerticalDragUpdate,
    this.onVerticalDragEnd,
    this.title,
    this.child,
  }) : super(key: key);

  final VoidCallback onTap;
  final GestureDragUpdateCallback onVerticalDragUpdate;
  final GestureDragEndCallback onVerticalDragEnd;
  final Widget title;
  final Widget child;

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
167
    return Material(
168 169
      elevation: 2.0,
      borderRadius: const BorderRadius.only(
170 171
        topLeft: Radius.circular(16.0),
        topRight: Radius.circular(16.0),
172
      ),
173
      child: Column(
174 175
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
176
          GestureDetector(
177 178 179 180
            behavior: HitTestBehavior.opaque,
            onVerticalDragUpdate: onVerticalDragUpdate,
            onVerticalDragEnd: onVerticalDragEnd,
            onTap: onTap,
181
            child: Container(
182 183 184
              height: 48.0,
              padding: const EdgeInsetsDirectional.only(start: 16.0),
              alignment: AlignmentDirectional.centerStart,
185
              child: DefaultTextStyle(
186
                style: theme.textTheme.subhead,
187
                child: Tooltip(
188 189 190
                  message: 'Tap to dismiss',
                  child: title,
                ),
191 192 193 194
              ),
            ),
          ),
          const Divider(height: 1.0),
195
          Expanded(child: child),
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
        ],
      ),
    );
  }
}

// Cross fades between 'Select a Category' and 'Asset Viewer'.
class BackdropTitle extends AnimatedWidget {
  const BackdropTitle({
    Key key,
    Listenable listenable,
  }) : super(key: key, listenable: listenable);

  @override
  Widget build(BuildContext context) {
    final Animation<double> animation = listenable;
212
    return DefaultTextStyle(
213 214 215
      style: Theme.of(context).primaryTextTheme.title,
      softWrap: false,
      overflow: TextOverflow.ellipsis,
216
      child: Stack(
217
        children: <Widget>[
218 219 220
          Opacity(
            opacity: CurvedAnimation(
              parent: ReverseAnimation(animation),
221 222 223 224
              curve: const Interval(0.5, 1.0),
            ).value,
            child: const Text('Select a Category'),
          ),
225 226
          Opacity(
            opacity: CurvedAnimation(
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
              parent: animation,
              curve: const Interval(0.5, 1.0),
            ).value,
            child: const Text('Asset Viewer'),
          ),
        ],
      ),
    );
  }
}

// This widget is essentially the backdrop itself.
class BackdropDemo extends StatefulWidget {
  static const String routeName = '/material/backdrop';

  @override
243
  _BackdropDemoState createState() => _BackdropDemoState();
244 245 246
}

class _BackdropDemoState extends State<BackdropDemo> with SingleTickerProviderStateMixin {
247
  final GlobalKey _backdropKey = GlobalKey(debugLabel: 'Backdrop');
248 249 250 251 252 253
  AnimationController _controller;
  Category _category = allCategories[0];

  @override
  void initState() {
    super.initState();
254
    _controller = AnimationController(
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
      duration: const Duration(milliseconds: 300),
      value: 1.0,
      vsync: this,
    );
  }

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

  void _changeCategory(Category category) {
    setState(() {
      _category = category;
      _controller.fling(velocity: 2.0);
    });
  }

  bool get _backdropPanelVisible {
    final AnimationStatus status = _controller.status;
    return status == AnimationStatus.completed || status == AnimationStatus.forward;
  }

  void _toggleBackdropPanelVisibility() {
    _controller.fling(velocity: _backdropPanelVisible ? -2.0 : 2.0);
  }

  double get _backdropHeight {
    final RenderBox renderBox = _backdropKey.currentContext.findRenderObject();
    return renderBox.size.height;
  }

  // By design: the panel can only be opened with a swipe. To close the panel
  // the user must either tap its heading or the backdrop's menu icon.

  void _handleDragUpdate(DragUpdateDetails details) {
    if (_controller.isAnimating || _controller.status == AnimationStatus.completed)
      return;

    _controller.value -= details.primaryDelta / (_backdropHeight ?? details.primaryDelta);
  }

  void _handleDragEnd(DragEndDetails details) {
    if (_controller.isAnimating || _controller.status == AnimationStatus.completed)
      return;

    final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight;
    if (flingVelocity < 0.0)
      _controller.fling(velocity: math.max(2.0, -flingVelocity));
    else if (flingVelocity > 0.0)
      _controller.fling(velocity: math.min(-2.0, -flingVelocity));
    else
      _controller.fling(velocity: _controller.value < 0.5 ? -2.0 : 2.0);
  }

  // Stacks a BackdropPanel, which displays the selected category, on top
  // of the backdrop. The categories are displayed with ListTiles. Just one
  // can be selected at a time. This is a LayoutWidgetBuild function because
  // we need to know how big the BackdropPanel will be to set up its
  // animation.
  Widget _buildStack(BuildContext context, BoxConstraints constraints) {
    const double panelTitleHeight = 48.0;
    final Size panelSize = constraints.biggest;
    final double panelTop = panelSize.height - panelTitleHeight;

321 322
    final Animation<RelativeRect> panelAnimation = RelativeRectTween(
      begin: RelativeRect.fromLTRB(
323 324 325 326 327
        0.0,
        panelTop - MediaQuery.of(context).padding.bottom,
        0.0,
        panelTop - panelSize.height,
      ),
328 329
      end: const RelativeRect.fromLTRB(0.0, 0.0, 0.0, 0.0),
    ).animate(
330
      CurvedAnimation(
331 332 333 334 335 336 337 338
        parent: _controller,
        curve: Curves.linear,
      ),
    );

    final ThemeData theme = Theme.of(context);
    final List<Widget> backdropItems = allCategories.map<Widget>((Category category) {
      final bool selected = category == _category;
339
      return Material(
340
        shape: const RoundedRectangleBorder(
341
          borderRadius: BorderRadius.all(Radius.circular(4.0)),
342 343 344 345
        ),
        color: selected
          ? Colors.white.withOpacity(0.25)
          : Colors.transparent,
346 347
        child: ListTile(
          title: Text(category.title),
348 349 350 351 352 353
          selected: selected,
          onTap: () {
            _changeCategory(category);
          },
        ),
      );
354
    }).toList();
355

356
    return Container(
357 358
      key: _backdropKey,
      color: theme.primaryColor,
359
      child: Stack(
360
        children: <Widget>[
361
          ListTileTheme(
362 363 364
            iconColor: theme.primaryIconTheme.color,
            textColor: theme.primaryTextTheme.title.color.withOpacity(0.6),
            selectedColor: theme.primaryTextTheme.title.color,
365
            child: Padding(
366
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
367
              child: Column(
368 369 370 371 372
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: backdropItems,
              ),
            ),
          ),
373
          PositionedTransition(
374
            rect: panelAnimation,
375
            child: BackdropPanel(
376 377 378
              onTap: _toggleBackdropPanelVisibility,
              onVerticalDragUpdate: _handleDragUpdate,
              onVerticalDragEnd: _handleDragEnd,
379 380
              title: Text(_category.title),
              child: CategoryView(category: _category),
381 382 383 384 385 386 387 388 389
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
390 391
    return Scaffold(
      appBar: AppBar(
392
        elevation: 0.0,
393
        title: BackdropTitle(
394 395
          listenable: _controller.view,
        ),
396
        actions: <Widget>[
397
          IconButton(
398
            onPressed: _toggleBackdropPanelVisibility,
399
            icon: AnimatedIcon(
400 401 402 403 404
              icon: AnimatedIcons.close_menu,
              progress: _controller.view,
            ),
          ),
        ],
405
      ),
406
      body: LayoutBuilder(
407 408 409 410 411
        builder: _buildStack,
      ),
    );
  }
}