backdrop_demo.dart 11.7 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// 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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    return Scrollbar(
      child: ListView(
        key: PageStorageKey<Category>(category),
        padding: const EdgeInsets.symmetric(
          vertical: 16.0,
          horizontal: 64.0,
        ),
        children: category.assets.map<Widget>((String asset) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Card(
                child: Container(
                  width: 144.0,
                  alignment: Alignment.center,
                  child: Column(
                    children: <Widget>[
                      Image.asset(
123
                        asset,
124 125 126 127 128 129 130 131 132 133
                        package: 'flutter_gallery_assets',
                        fit: BoxFit.contain,
                      ),
                      Container(
                        padding: const EdgeInsets.only(bottom: 16.0),
                        alignment: AlignmentDirectional.center,
                        child: Text(
                          asset,
                          style: theme.textTheme.caption,
                        ),
134
                      ),
135 136
                    ],
                  ),
137 138
                ),
              ),
139 140 141 142
              const SizedBox(height: 24.0),
            ],
          );
        }).toList(),
143
      ),
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    );
  }
}

// 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);
169
    return Material(
170 171
      elevation: 2.0,
      borderRadius: const BorderRadius.only(
172 173
        topLeft: Radius.circular(16.0),
        topRight: Radius.circular(16.0),
174
      ),
175
      child: Column(
176 177
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
178
          GestureDetector(
179 180 181 182
            behavior: HitTestBehavior.opaque,
            onVerticalDragUpdate: onVerticalDragUpdate,
            onVerticalDragEnd: onVerticalDragEnd,
            onTap: onTap,
183
            child: Container(
184 185 186
              height: 48.0,
              padding: const EdgeInsetsDirectional.only(start: 16.0),
              alignment: AlignmentDirectional.centerStart,
187
              child: DefaultTextStyle(
188
                style: theme.textTheme.subtitle1,
189
                child: Tooltip(
190 191 192
                  message: 'Tap to dismiss',
                  child: title,
                ),
193 194 195 196
              ),
            ),
          ),
          const Divider(height: 1.0),
197
          Expanded(child: child),
198 199 200 201 202 203 204 205 206 207
        ],
      ),
    );
  }
}

// Cross fades between 'Select a Category' and 'Asset Viewer'.
class BackdropTitle extends AnimatedWidget {
  const BackdropTitle({
    Key key,
208
    Animation<double> listenable,
209 210 211 212
  }) : super(key: key, listenable: listenable);

  @override
  Widget build(BuildContext context) {
213
    final Animation<double> animation = listenable as Animation<double>;
214
    return DefaultTextStyle(
215
      style: Theme.of(context).primaryTextTheme.headline6,
216 217
      softWrap: false,
      overflow: TextOverflow.ellipsis,
218
      child: Stack(
219
        children: <Widget>[
220 221 222
          Opacity(
            opacity: CurvedAnimation(
              parent: ReverseAnimation(animation),
223 224 225 226
              curve: const Interval(0.5, 1.0),
            ).value,
            child: const Text('Select a Category'),
          ),
227 228
          Opacity(
            opacity: CurvedAnimation(
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
              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
245
  _BackdropDemoState createState() => _BackdropDemoState();
246 247 248
}

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

  @override
  void initState() {
    super.initState();
256
    _controller = AnimationController(
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
      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 {
286
    final RenderBox renderBox = _backdropKey.currentContext.findRenderObject() as RenderBox;
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 321 322
    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;

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

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

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

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