card_collection.dart 12.7 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 6
import 'dart:math';

7
import 'package:flutter/material.dart';
8

9
class CardModel {
10
  CardModel(this.value, this.height) :
11
    textController = TextEditingController(text: 'Item $value');
12

13 14
  int value;
  double height;
15
  int get color => ((value % 9) + 1) * 100;
16
  final TextEditingController textController;
17
  Key get key => ObjectKey(this);
18 19
}

20
class CardCollection extends StatefulWidget {
21
  const CardCollection({Key? key}) : super(key: key);
22

23
  @override
24
  CardCollectionState createState() => CardCollectionState();
25 26
}

27
class CardCollectionState extends State<CardCollection> {
28

29
  static const TextStyle cardLabelStyle =
30
    TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold);
31

Hans Muller's avatar
Hans Muller committed
32
  // TODO(hansmuller): need a local image asset
33
  static const String _sunshineURL = 'http://www.walltor.com/images/wallpaper/good-morning-sunshine-58540.jpg';
Hans Muller's avatar
Hans Muller committed
34

35
  static const double kCardMargins = 8.0;
36
  static const double kFixedCardHeight = 100.0;
37
  static const List<double> _cardHeights = <double>[
38 39 40 41
    48.0, 63.0, 85.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
    48.0, 63.0, 85.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
    48.0, 63.0, 85.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
  ];
42

43
  MaterialColor _primaryColor = Colors.deepPurple;
44
  List<CardModel> _cardModels = <CardModel>[];
45
  DismissDirection _dismissDirection = DismissDirection.horizontal;
46
  TextAlign _textAlign = TextAlign.center;
Hans Muller's avatar
Hans Muller committed
47
  bool _editable = false;
48
  bool _fixedSizeCards = false;
Hans Muller's avatar
Hans Muller committed
49
  bool _sunshine = false;
50
  bool _varyFontSizes = false;
51

52 53 54
  void _updateCardSizes() {
    if (_fixedSizeCards)
      return;
55
    _cardModels = List<CardModel>.generate(
56 57 58 59
      _cardModels.length,
      (int i) {
        _cardModels[i].height = _editable ? max(_cardHeights[i], 60.0) : _cardHeights[i];
        return _cardModels[i];
60
      },
61 62 63
    );
  }

64
  void _initVariableSizedCardModels() {
65
    _cardModels = List<CardModel>.generate(
66
      _cardHeights.length,
67
      (int i) => CardModel(i, _editable ? max(_cardHeights[i], 60.0) : _cardHeights[i]),
Hixie's avatar
Hixie committed
68
    );
69 70
  }

71 72
  void _initFixedSizedCardModels() {
    const int cardCount = 27;
73
    _cardModels = List<CardModel>.generate(
Hixie's avatar
Hixie committed
74
      cardCount,
75
      (int i) => CardModel(i, kFixedCardHeight),
Hixie's avatar
Hixie committed
76
    );
77 78 79 80 81 82 83 84 85
  }

  void _initCardModels() {
    if (_fixedSizeCards)
      _initFixedSizedCardModels();
    else
      _initVariableSizedCardModels();
  }

86
  @override
87 88
  void initState() {
    super.initState();
89 90 91
    _initCardModels();
  }

92
  void dismissCard(CardModel card) {
93
    if (_cardModels.contains(card)) {
94
      setState(() {
95
        _cardModels.remove(card);
96 97 98 99
      });
    }
  }

100
  Widget _buildDrawer() {
101 102
    return Drawer(
      child: IconTheme(
Adam Barth's avatar
Adam Barth committed
103
        data: const IconThemeData(color: Colors.black),
104
        child: ListView(
105
          children: <Widget>[
106
            const DrawerHeader(child: Center(child: Text('Options'))),
107 108 109 110
            buildDrawerCheckbox('Make card labels editable', _editable, _toggleEditable),
            buildDrawerCheckbox('Fixed size cards', _fixedSizeCards, _toggleFixedSizeCards),
            buildDrawerCheckbox('Let the sun shine', _sunshine, _toggleSunshine),
            buildDrawerCheckbox('Vary font sizes', _varyFontSizes, _toggleVaryFontSizes, enabled: !_editable),
111
            const Divider(),
112 113 114 115
            buildDrawerColorRadioItem('Deep Purple', Colors.deepPurple, _primaryColor, _selectColor),
            buildDrawerColorRadioItem('Green', Colors.green, _primaryColor, _selectColor),
            buildDrawerColorRadioItem('Amber', Colors.amber, _primaryColor, _selectColor),
            buildDrawerColorRadioItem('Teal', Colors.teal, _primaryColor, _selectColor),
116
            const Divider(),
117 118 119
            buildDrawerDirectionRadioItem('Dismiss horizontally', DismissDirection.horizontal, _dismissDirection, _changeDismissDirection, icon: Icons.code),
            buildDrawerDirectionRadioItem('Dismiss left', DismissDirection.endToStart, _dismissDirection, _changeDismissDirection, icon: Icons.arrow_back),
            buildDrawerDirectionRadioItem('Dismiss right', DismissDirection.startToEnd, _dismissDirection, _changeDismissDirection, icon: Icons.arrow_forward),
120
            const Divider(),
121 122 123
            buildFontRadioItem('Left-align text', TextAlign.left, _textAlign, _changeTextAlign, icon: Icons.format_align_left, enabled: !_editable),
            buildFontRadioItem('Center-align text', TextAlign.center, _textAlign, _changeTextAlign, icon: Icons.format_align_center, enabled: !_editable),
            buildFontRadioItem('Right-align text', TextAlign.right, _textAlign, _changeTextAlign, icon: Icons.format_align_right, enabled: !_editable),
124
            const Divider(),
125
            ListTile(
126
              leading: const Icon(Icons.dvr),
127
              onTap: () { debugDumpApp(); debugDumpRenderTree(); },
128
              title: const Text('Dump App to Console'),
129
            ),
130 131 132
          ],
        ),
      ),
133
    );
134 135
  }

136
  String _dismissDirectionText(DismissDirection direction) {
137
    final String s = direction.toString();
138 139 140
    return "dismiss ${s.substring(s.indexOf('.') + 1)}";
  }

Hixie's avatar
Hixie committed
141 142 143
  void _toggleEditable() {
    setState(() {
      _editable = !_editable;
144
      _updateCardSizes();
Hixie's avatar
Hixie committed
145 146 147
    });
  }

148 149 150 151 152 153 154
  void _toggleFixedSizeCards() {
    setState(() {
      _fixedSizeCards = !_fixedSizeCards;
      _initCardModels();
    });
  }

Hans Muller's avatar
Hans Muller committed
155 156 157 158 159 160
  void _toggleSunshine() {
    setState(() {
      _sunshine = !_sunshine;
    });
  }

161 162 163 164 165 166
  void _toggleVaryFontSizes() {
    setState(() {
      _varyFontSizes = !_varyFontSizes;
    });
  }

167
  void _selectColor(MaterialColor? selection) {
168
    setState(() {
169
      _primaryColor = selection!;
170 171 172
    });
  }

173
  void _changeDismissDirection(DismissDirection? newDismissDirection) {
174
    setState(() {
175
      _dismissDirection = newDismissDirection!;
176
    });
Hixie's avatar
Hixie committed
177 178
  }

179
  void _changeTextAlign(TextAlign? newTextAlign) {
Hixie's avatar
Hixie committed
180
    setState(() {
181
      _textAlign = newTextAlign!;
Hixie's avatar
Hixie committed
182
    });
183 184
  }

185
  Widget buildDrawerCheckbox(String label, bool value, void Function() callback, { bool enabled = true }) {
186
    return ListTile(
187
      onTap: enabled ? callback : null,
188 189
      title: Text(label),
      trailing: Checkbox(
190 191
        value: value,
        onChanged: enabled ? (_) { callback(); } : null,
192
      ),
193 194
    );
  }
195

196
  Widget buildDrawerColorRadioItem(String label, MaterialColor itemValue, MaterialColor currentValue, ValueChanged<MaterialColor?> onChanged, { IconData? icon, bool enabled = true }) {
197 198 199
    return ListTile(
      leading: Icon(icon),
      title: Text(label),
200
      onTap: enabled ? () { onChanged(itemValue); } : null,
201
      trailing: Radio<MaterialColor>(
202 203 204
        value: itemValue,
        groupValue: currentValue,
        onChanged: enabled ? onChanged : null,
205
      ),
Hixie's avatar
Hixie committed
206 207 208
    );
  }

209
  Widget buildDrawerDirectionRadioItem(String label, DismissDirection itemValue, DismissDirection currentValue, ValueChanged<DismissDirection?> onChanged, { IconData? icon, bool enabled = true }) {
210 211 212
    return ListTile(
      leading: Icon(icon),
      title: Text(label),
213
      onTap: enabled ? () { onChanged(itemValue); } : null,
214
      trailing: Radio<DismissDirection>(
215 216 217
        value: itemValue,
        groupValue: currentValue,
        onChanged: enabled ? onChanged : null,
218
      ),
Hixie's avatar
Hixie committed
219 220 221
    );
  }

222
  Widget buildFontRadioItem(String label, TextAlign itemValue, TextAlign currentValue, ValueChanged<TextAlign?> onChanged, { IconData? icon, bool enabled = true }) {
223 224 225
    return ListTile(
      leading: Icon(icon),
      title: Text(label),
226
      onTap: enabled ? () { onChanged(itemValue); } : null,
227
      trailing: Radio<TextAlign>(
228 229 230
        value: itemValue,
        groupValue: currentValue,
        onChanged: enabled ? onChanged : null,
231
      ),
232 233 234
    );
  }

235
  AppBar _buildAppBar(BuildContext context) {
236
    return AppBar(
237
      actions: <Widget>[
238
        Text(_dismissDirectionText(_dismissDirection)),
Hans Muller's avatar
Hans Muller committed
239
      ],
240
      flexibleSpace: Container(
241 242
        padding: const EdgeInsets.only(left: 72.0),
        height: 128.0,
243
        alignment: const Alignment(-1.0, 0.5),
244
        child: Text('Swipe Away: ${_cardModels.length}', style: Theme.of(context).primaryTextTheme.headline6),
245
      ),
246 247 248
    );
  }

249
  Widget _buildCard(BuildContext context, int index) {
250
    final CardModel cardModel = _cardModels[index];
251 252
    final Widget card = Dismissible(
      key: ObjectKey(cardModel),
253
      direction: _dismissDirection,
254
      onDismissed: (DismissDirection direction) { dismissCard(cardModel); },
255
      child: Card(
256
        color: _primaryColor[cardModel.color],
257
        child: Container(
258
          height: cardModel.height,
259
          padding: const EdgeInsets.all(kCardMargins),
260
          child: _editable ?
261 262 263
            Center(
              child: TextField(
                key: GlobalObjectKey(cardModel),
264
                controller: cardModel.textController,
265
              ),
266
            )
267
          : DefaultTextStyle.merge(
268
              style: cardLabelStyle.copyWith(
269
                fontSize: _varyFontSizes ? 5.0 + index : null
270
              ),
271
              child: Column(
272
                crossAxisAlignment: CrossAxisAlignment.stretch,
273 274
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
275
                  Text(cardModel.textController.text, textAlign: _textAlign),
276 277 278 279 280
                ],
              ),
            ),
        ),
      ),
281 282
    );

283
    String backgroundMessage;
284
    switch (_dismissDirection) {
285
      case DismissDirection.horizontal:
286
        backgroundMessage = 'Swipe in either direction';
287
        break;
288
      case DismissDirection.endToStart:
289
        backgroundMessage = 'Swipe left to dismiss';
290
        break;
291
      case DismissDirection.startToEnd:
292
        backgroundMessage = 'Swipe right to dismiss';
293 294
        break;
      default:
295
        backgroundMessage = 'Unsupported dismissDirection';
296 297
    }

298
    // TODO(abarth): This icon is wrong in RTL.
299
    Widget leftArrowIcon = const Icon(Icons.arrow_back, size: 36.0);
300
    if (_dismissDirection == DismissDirection.startToEnd)
301
      leftArrowIcon = Opacity(opacity: 0.1, child: leftArrowIcon);
302

303
      // TODO(abarth): This icon is wrong in RTL.
304
    Widget rightArrowIcon = const Icon(Icons.arrow_forward, size: 36.0);
305
    if (_dismissDirection == DismissDirection.endToStart)
306
      rightArrowIcon = Opacity(opacity: 0.1, child: rightArrowIcon);
307

308
    final ThemeData theme = Theme.of(context);
309
    final TextStyle? backgroundTextStyle = theme.primaryTextTheme.headline6;
310

311
    // The background Widget appears behind the Dismissible card when the card
312 313 314 315
    // moves to the left or right. The Positioned widget ensures that the
    // size of the background,card Stack will be based only on the card. The
    // Viewport ensures that when the card's resize animation occurs, the
    // background (text and icons) will just be clipped, not resized.
316 317
    final Widget background = Positioned.fill(
      child: Container(
318
        margin: const EdgeInsets.all(4.0),
319 320
        child: SingleChildScrollView(
          child: Container(
321
            height: cardModel.height,
322
            color: theme.primaryColor,
323
            child: Row(
324 325
              children: <Widget>[
                leftArrowIcon,
326 327
                Expanded(
                  child: Text(backgroundMessage,
328
                    style: backgroundTextStyle,
329 330
                    textAlign: TextAlign.center,
                  ),
331
                ),
332 333 334 335 336 337
                rightArrowIcon,
              ],
            ),
          ),
        ),
      ),
338
    );
339

340
    return IconTheme(
341
      key: cardModel.key,
Adam Barth's avatar
Adam Barth committed
342
      data: const IconThemeData(color: Colors.white),
343
      child: Stack(children: <Widget>[background, card]),
344
    );
345 346
  }

347
  Shader _createShader(Rect bounds) {
348
    return const LinearGradient(
349 350
        begin: Alignment.topCenter,
        end: Alignment.bottomCenter,
351 352
        colors: <Color>[Color(0x00FFFFFF), Color(0xFFFFFFFF)],
        stops: <double>[0.1, 0.35],
Hans Muller's avatar
Hans Muller committed
353
    )
Adam Barth's avatar
Adam Barth committed
354
    .createShader(bounds);
Hans Muller's avatar
Hans Muller committed
355 356
  }

357
  @override
358
  Widget build(BuildContext context) {
359
    Widget cardCollection = ListView.builder(
360 361 362 363
      itemExtent: _fixedSizeCards ? kFixedCardHeight : null,
      itemCount: _cardModels.length,
      itemBuilder: _buildCard,
    );
364

365
    if (_sunshine) {
366
      cardCollection = Stack(
367
        children: <Widget>[
368
          Column(children: <Widget>[Image.network(_sunshineURL)]),
369
          ShaderMask(shaderCallback: _createShader, child: cardCollection),
370
        ],
371 372
      );
    }
Hans Muller's avatar
Hans Muller committed
373

374
    final Widget body = Container(
375
      padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
376
      color: _primaryColor.shade50,
377
      child: cardCollection,
378 379
    );

380 381
    return Theme(
      data: ThemeData(
382
        primarySwatch: _primaryColor,
383
      ),
384
      child: Scaffold(
385
        appBar: _buildAppBar(context),
386
        drawer: _buildDrawer(),
387 388
        body: body,
      ),
389 390 391 392 393
    );
  }
}

void main() {
394
  runApp(const MaterialApp(
395
    title: 'Cards',
396
    home: CardCollection(),
397
  ));
398
}