ExpansionTiles可用于生成两级或多级列表。

    Android screenshot

    这个应用程序用ExpansionTiles显示分层数据。点击一个标题会展开或折叠其子视图。

    当它显示在一个可滚动的组件中时,如使用ListView.builder()创建列表,这时ExpansionTiles可能非常有用,特别是对于Material Design中的“展开/折叠”列表。

    通过flutter create命令创建一个新项目,并用下面的代码替换lib/main.dart的内容来尝试运行一下。

    1. // Copyright 2017 The Chromium Authors. All rights reserved.
    2. // Use of this source code is governed by a BSD-style license that can be
    3. // found in the LICENSE file.
    4. import 'package:flutter/material.dart';
    5. class ExpansionTileSample extends StatelessWidget {
    6. @override
    7. Widget build(BuildContext context) {
    8. return new MaterialApp(
    9. home: new Scaffold(
    10. appBar: new AppBar(
    11. title: const Text('ExpansionTile'),
    12. ),
    13. body: new ListView.builder(
    14. itemBuilder: (BuildContext context, int index) => new EntryItem(data[index]),
    15. itemCount: data.length,
    16. ),
    17. ),
    18. );
    19. }
    20. }
    21. // One entry in the multilevel list displayed by this app.
    22. class Entry {
    23. Entry(this.title, [this.children = const <Entry>[]]);
    24. final String title;
    25. final List<Entry> children;
    26. }
    27. // The entire multilevel list displayed by this app.
    28. final List<Entry> data = <Entry>[
    29. new Entry('Chapter A',
    30. <Entry>[
    31. new Entry('Section A0',
    32. <Entry>[
    33. new Entry('Item A0.1'),
    34. new Entry('Item A0.2'),
    35. new Entry('Item A0.3'),
    36. ],
    37. ),
    38. new Entry('Section A1'),
    39. new Entry('Section A2'),
    40. ],
    41. ),
    42. new Entry('Chapter B',
    43. <Entry>[
    44. new Entry('Section B0'),
    45. new Entry('Section B1'),
    46. ],
    47. ),
    48. new Entry('Chapter C',
    49. <Entry>[
    50. new Entry('Section C0'),
    51. new Entry('Section C1'),
    52. new Entry('Section C2',
    53. <Entry>[
    54. new Entry('Item C2.0'),
    55. new Entry('Item C2.1'),
    56. new Entry('Item C2.2'),
    57. new Entry('Item C2.3'),
    58. ],
    59. ),
    60. ],
    61. ),
    62. ];
    63. // Displays one Entry. If the entry has children then it's displayed
    64. // with an ExpansionTile.
    65. class EntryItem extends StatelessWidget {
    66. const EntryItem(this.entry);
    67. final Entry entry;
    68. Widget _buildTiles(Entry root) {
    69. if (root.children.isEmpty)
    70. return new ListTile(title: new Text(root.title));
    71. return new ExpansionTile(
    72. key: new PageStorageKey<Entry>(root),
    73. title: new Text(root.title),
    74. children: root.children.map(_buildTiles).toList(),
    75. );
    76. }
    77. @override
    78. Widget build(BuildContext context) {
    79. return _buildTiles(entry);
    80. }
    81. }
    82. void main() {
    83. runApp(new ExpansionTileSample());
    84. }

    也可以看看: