card_collection.dart 12.6 KB
Newer Older
1 2 3 4
// Copyright 2015 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.

5
import 'package:flutter/material.dart';
6
import 'package:flutter/rendering.dart' show debugDumpRenderTree;
7

8
class CardModel {
9
  CardModel(this.value, this.height) {
10
    textController = new TextEditingController(text: 'Item $value');
11
  }
12 13
  int value;
  double height;
14
  int get color => ((value % 9) + 1) * 100;
15
  TextEditingController textController;
Hixie's avatar
Hixie committed
16
  Key get key => new ObjectKey(this);
17 18
}

19
class CardCollection extends StatefulWidget {
20
  @override
21
  CardCollectionState createState() => new CardCollectionState();
22 23
}

24
class CardCollectionState extends State<CardCollection> {
25

26
  static const TextStyle cardLabelStyle =
27
    const TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold);
28

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

32
  static const double kCardMargins = 8.0;
33
  static const double kFixedCardHeight = 100.0;
34

35
  MaterialColor _primaryColor = Colors.deepPurple;
36 37
  List<CardModel> _cardModels;
  DismissDirection _dismissDirection = DismissDirection.horizontal;
38
  TextAlign _textAlign = TextAlign.center;
Hans Muller's avatar
Hans Muller committed
39
  bool _editable = false;
40
  bool _fixedSizeCards = false;
Hans Muller's avatar
Hans Muller committed
41
  bool _sunshine = false;
42
  bool _varyFontSizes = false;
43

44
  void _initVariableSizedCardModels() {
45
    final List<double> cardHeights = <double>[
46 47
      48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
      48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48
      48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
49
    ];
Hixie's avatar
Hixie committed
50 51 52 53
    _cardModels = new List<CardModel>.generate(
      cardHeights.length,
      (int i) => new CardModel(i, cardHeights[i])
    );
54 55
  }

56 57
  void _initFixedSizedCardModels() {
    const int cardCount = 27;
Hixie's avatar
Hixie committed
58 59
    _cardModels = new List<CardModel>.generate(
      cardCount,
60
      (int i) => new CardModel(i, kFixedCardHeight),
Hixie's avatar
Hixie committed
61
    );
62 63 64 65 66 67 68 69 70
  }

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

71
  @override
72 73
  void initState() {
    super.initState();
74 75 76
    _initCardModels();
  }

77
  void dismissCard(CardModel card) {
78
    if (_cardModels.contains(card)) {
79
      setState(() {
80
        _cardModels.remove(card);
81 82 83 84
      });
    }
  }

85 86
  Widget _buildDrawer() {
    return new Drawer(
87
      child: new IconTheme(
Adam Barth's avatar
Adam Barth committed
88
        data: const IconThemeData(color: Colors.black),
89
        child: new ListView(
90
          children: <Widget>[
91
            const DrawerHeader(child: const Center(child: const Text('Options'))),
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
            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),
            new Divider(),
            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),
            new Divider(),
            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),
            new Divider(),
            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),
            new Divider(),
110
            new ListTile(
111
              leading: const Icon(Icons.dvr),
112
              onTap: () { debugDumpApp(); debugDumpRenderTree(); },
113
              title: const Text('Dump App to Console'),
114
            ),
115 116 117
          ],
        ),
      ),
118
    );
119 120
  }

121
  String _dismissDirectionText(DismissDirection direction) {
122
    final String s = direction.toString();
123 124 125
    return "dismiss ${s.substring(s.indexOf('.') + 1)}";
  }

Hixie's avatar
Hixie committed
126 127 128 129 130 131
  void _toggleEditable() {
    setState(() {
      _editable = !_editable;
    });
  }

132 133 134 135 136 137 138
  void _toggleFixedSizeCards() {
    setState(() {
      _fixedSizeCards = !_fixedSizeCards;
      _initCardModels();
    });
  }

Hans Muller's avatar
Hans Muller committed
139 140 141 142 143 144
  void _toggleSunshine() {
    setState(() {
      _sunshine = !_sunshine;
    });
  }

145 146 147 148 149 150
  void _toggleVaryFontSizes() {
    setState(() {
      _varyFontSizes = !_varyFontSizes;
    });
  }

151
  void _selectColor(MaterialColor selection) {
152 153 154 155 156
    setState(() {
      _primaryColor = selection;
    });
  }

157
  void _changeDismissDirection(DismissDirection newDismissDirection) {
158 159 160
    setState(() {
      _dismissDirection = newDismissDirection;
    });
Hixie's avatar
Hixie committed
161 162
  }

163
  void _changeTextAlign(TextAlign newTextAlign) {
Hixie's avatar
Hixie committed
164
    setState(() {
165
      _textAlign = newTextAlign;
Hixie's avatar
Hixie committed
166
    });
167 168
  }

169
  Widget buildDrawerCheckbox(String label, bool value, void callback(), { bool enabled: true }) {
170 171 172 173 174 175
    return new ListTile(
      onTap: enabled ? callback : null,
      title: new Text(label),
      trailing: new Checkbox(
        value: value,
        onChanged: enabled ? (_) { callback(); } : null,
176
      ),
177 178
    );
  }
179

180
  Widget buildDrawerColorRadioItem(String label, MaterialColor itemValue, MaterialColor currentValue, ValueChanged<MaterialColor> onChanged, { IconData icon, bool enabled: true }) {
181 182 183 184 185 186 187 188
    return new ListTile(
      leading: new Icon(icon),
      title: new Text(label),
      onTap: enabled ? () { onChanged(itemValue); } : null,
      trailing: new Radio<MaterialColor>(
        value: itemValue,
        groupValue: currentValue,
        onChanged: enabled ? onChanged : null,
189
      ),
Hixie's avatar
Hixie committed
190 191 192
    );
  }

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

206
  Widget buildFontRadioItem(String label, TextAlign itemValue, TextAlign currentValue, ValueChanged<TextAlign> onChanged, { IconData icon, bool enabled: true }) {
207 208 209 210 211 212 213 214
    return new ListTile(
      leading: new Icon(icon),
      title: new Text(label),
      onTap: enabled ? () { onChanged(itemValue); } : null,
      trailing: new Radio<TextAlign>(
        value: itemValue,
        groupValue: currentValue,
        onChanged: enabled ? onChanged : null,
215
      ),
216 217 218
    );
  }

219 220 221
  Widget _buildAppBar(BuildContext context) {
    return new AppBar(
      actions: <Widget>[
222
        new Text(_dismissDirectionText(_dismissDirection))
Hans Muller's avatar
Hans Muller committed
223
      ],
224 225 226
      flexibleSpace: new Container(
        padding: const EdgeInsets.only(left: 72.0),
        height: 128.0,
227
        alignment: const FractionalOffset(0.0, 0.75),
228 229
        child: new Text('Swipe Away: ${_cardModels.length}', style: Theme.of(context).primaryTextTheme.title),
      ),
230 231 232
    );
  }

233
  Widget _buildCard(BuildContext context, int index) {
234
    final CardModel cardModel = _cardModels[index];
235
    final Widget card = new Dismissible(
236
      key: new ObjectKey(cardModel),
237
      direction: _dismissDirection,
238
      onDismissed: (DismissDirection direction) { dismissCard(cardModel); },
239
      child: new Card(
240
        color: _primaryColor[cardModel.color],
241
        child: new Container(
242
          height: cardModel.height,
243
          padding: const EdgeInsets.all(kCardMargins),
244
          child: _editable ?
Hixie's avatar
Hixie committed
245
            new Center(
246
              child: new TextField(
247
                key: new GlobalObjectKey(cardModel),
248
                controller: cardModel.textController,
249
              ),
250
            )
251
          : DefaultTextStyle.merge(
252
              style: cardLabelStyle.copyWith(
253
                fontSize: _varyFontSizes ? 5.0 + index : null
254
              ),
255
              child: new Column(
256
                crossAxisAlignment: CrossAxisAlignment.stretch,
257 258
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
259
                  new Text(cardModel.textController.text, textAlign: _textAlign),
260 261 262 263 264
                ],
              ),
            ),
        ),
      ),
265 266
    );

267 268 269 270 271
    String backgroundMessage;
    switch(_dismissDirection) {
      case DismissDirection.horizontal:
        backgroundMessage = "Swipe in either direction";
        break;
272
      case DismissDirection.endToStart:
273 274
        backgroundMessage = "Swipe left to dismiss";
        break;
275
      case DismissDirection.startToEnd:
276 277 278 279 280 281
        backgroundMessage = "Swipe right to dismiss";
        break;
      default:
        backgroundMessage = "Unsupported dismissDirection";
    }

282
    // TODO(abarth): This icon is wrong in RTL.
283
    Widget leftArrowIcon =  const Icon(Icons.arrow_back, size: 36.0);
284
    if (_dismissDirection == DismissDirection.startToEnd)
285 286
      leftArrowIcon = new Opacity(opacity: 0.1, child: leftArrowIcon);

287
      // TODO(abarth): This icon is wrong in RTL.
288
    Widget rightArrowIcon =  const Icon(Icons.arrow_forward, size: 36.0);
289
    if (_dismissDirection == DismissDirection.endToStart)
290
      rightArrowIcon = new Opacity(opacity: 0.1, child: rightArrowIcon);
291

292 293 294
    final ThemeData theme = Theme.of(context);
    final TextStyle backgroundTextStyle = theme.primaryTextTheme.title;

295
    // The background Widget appears behind the Dismissible card when the card
296 297 298 299
    // 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.
300
    final Widget background = new Positioned.fill(
301
      child: new Container(
302
        margin: const EdgeInsets.all(4.0),
303
        child: new SingleChildScrollView(
304 305
          child: new Container(
            height: cardModel.height,
306
            color: theme.primaryColor,
307 308 309
            child: new Row(
              children: <Widget>[
                leftArrowIcon,
310
                new Expanded(
311 312
                  child: new Text(backgroundMessage,
                    style: backgroundTextStyle,
313 314
                    textAlign: TextAlign.center,
                  ),
315
                ),
316 317 318 319 320 321
                rightArrowIcon,
              ],
            ),
          ),
        ),
      ),
322
    );
323

324 325
    return new IconTheme(
      key: cardModel.key,
Adam Barth's avatar
Adam Barth committed
326
      data: const IconThemeData(color: Colors.white),
327
      child: new Stack(children: <Widget>[background, card]),
328
    );
329 330
  }

331
  Shader _createShader(Rect bounds) {
Hans Muller's avatar
Hans Muller committed
332
    return new LinearGradient(
333 334
        begin: FractionalOffset.topLeft,
        end: FractionalOffset.bottomLeft,
Hixie's avatar
Hixie committed
335
        colors: <Color>[const Color(0x00FFFFFF), const Color(0xFFFFFFFF)],
336
        stops: <double>[0.1, 0.35],
Hans Muller's avatar
Hans Muller committed
337
    )
Adam Barth's avatar
Adam Barth committed
338
    .createShader(bounds);
Hans Muller's avatar
Hans Muller committed
339 340
  }

341
  @override
342
  Widget build(BuildContext context) {
343 344 345 346 347
    Widget cardCollection = new ListView.builder(
      itemExtent: _fixedSizeCards ? kFixedCardHeight : null,
      itemCount: _cardModels.length,
      itemBuilder: _buildCard,
    );
348

349 350 351
    if (_sunshine) {
      cardCollection = new Stack(
        children: <Widget>[
352
          new Column(children: <Widget>[new Image.network(_sunshineURL)]),
353 354
          new ShaderMask(child: cardCollection, shaderCallback: _createShader),
        ],
355 356
      );
    }
Hans Muller's avatar
Hans Muller committed
357

358
    final Widget body = new Container(
359
      padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
360
      color: _primaryColor.shade50,
361
      child: cardCollection,
362 363
    );

364 365
    return new Theme(
      data: new ThemeData(
366
        primarySwatch: _primaryColor,
367 368
      ),
      child: new Scaffold(
369
        appBar: _buildAppBar(context),
370
        drawer: _buildDrawer(),
371 372
        body: body,
      ),
373 374 375 376 377
    );
  }
}

void main() {
Adam Barth's avatar
Adam Barth committed
378
  runApp(new MaterialApp(
379
    title: 'Cards',
380
    home: new CardCollection(),
381
  ));
382
}