Flutter - 点击展开和收起ExpansionTile

12

我将这个作为扩展和折叠扩展平铺的参考-------Flutter - 选择项目后折叠ExpansionTile

我想要的是,如果一个扩展平铺处于打开状态,当用户点击另一个时,其他已打开的扩展平铺应该关闭。

我的应用程序截图

import 'package:flutter/material.dart';
import 'package:meta/meta.dart';

void main() {
  runApp(new ExpansionTileSample());
}

class ExpansionTileSample extends StatefulWidget {
  @override
  ExpansionTileSampleState createState() => new ExpansionTileSampleState();
}

class ExpansionTileSampleState extends State<ExpansionTileSample> {
  final GlobalKey<AppExpansionTileState> expansionTile = new GlobalKey();
  String foos = 'One';

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('ExpansionTile'),
        ),
        body: GestureDetector(
          onTap: () {
            setState(() {
             // this.foos = 'One';
              expansionTile.currentState.collapse();
            });
          },
          child: Column(
            children: <Widget>[
              new AppExpansionTile(
                  key: expansionTile,
                  title: new Text('1-3'),
                  backgroundColor:
                      Theme.of(context).accentColor.withOpacity(0.025),
                  children: <Widget>[
                    new ListTile(
                      title: const Text('One'),
                    ),
                    new ListTile(
                      title: const Text('Two'),
                    ),
                    new ListTile(
                      title: const Text('Three'),
                    ),
                  ]),
              new AppExpansionTile(
                  title: new Text('4-6'),
                  backgroundColor:
                      Theme.of(context).accentColor.withOpacity(0.025),
                  children: <Widget>[
                    new ListTile(
                      title: const Text('four'),
                    ),
                    new ListTile(
                      title: const Text('five'),
                    ),
                    new ListTile(
                      title: const Text('six'),
                    ),
                  ]),
              new AppExpansionTile(
                  title: new Text('6-9'),
                  backgroundColor:
                      Theme.of(context).accentColor.withOpacity(0.025),
                  children: <Widget>[
                    new ListTile(
                      title: const Text('seven'),
                    ),
                    new ListTile(
                      title: const Text('eight'),
                    ),
                    new ListTile(
                      title: const Text('nine'),
                    ),
                  ]),
            ],
          ),
        ),
      ),
    );
  }
}

// --- Copied and slightly modified version of the ExpansionTile.

const Duration _kExpand = const Duration(milliseconds: 200);

class AppExpansionTile extends StatefulWidget {
  const AppExpansionTile({
    Key key,
    this.leading,
    @required this.title,
    this.backgroundColor,
    this.onExpansionChanged,
    this.children: const <Widget>[],
    this.trailing,
    this.initiallyExpanded: false,
  })  : assert(initiallyExpanded != null),
        super(key: key);

  final Widget leading;
  final Widget title;
  final ValueChanged<bool> onExpansionChanged;
  final List<Widget> children;
  final Color backgroundColor;
  final Widget trailing;
  final bool initiallyExpanded;

  @override
  AppExpansionTileState createState() => new AppExpansionTileState();
}

class AppExpansionTileState extends State<AppExpansionTile>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  CurvedAnimation _easeOutAnimation;
  CurvedAnimation _easeInAnimation;
  ColorTween _borderColor;
  ColorTween _headerColor;
  ColorTween _iconColor;
  ColorTween _backgroundColor;
  Animation<double> _iconTurns;

  bool _isExpanded = false;

  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(duration: _kExpand, vsync: this);
    _easeOutAnimation =
        new CurvedAnimation(parent: _controller, curve: Curves.easeOut);
    _easeInAnimation =
        new CurvedAnimation(parent: _controller, curve: Curves.easeIn);
    _borderColor = new ColorTween();
    _headerColor = new ColorTween();
    _iconColor = new ColorTween();
    _iconTurns =
        new Tween<double>(begin: 0.0, end: 0.5).animate(_easeInAnimation);
    _backgroundColor = new ColorTween();

    _isExpanded =
        PageStorage.of(context)?.readState(context) ?? widget.initiallyExpanded;
    if (_isExpanded) _controller.value = 1.0;
  }

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

  void expand() {
    _setExpanded(true);
  }

  void collapse() {
    _setExpanded(false);
  }

  void toggle() {
    _setExpanded(!_isExpanded);
  }

  void _setExpanded(bool isExpanded) {
    if (_isExpanded != isExpanded) {
      setState(() {
        _isExpanded = isExpanded;
        if (_isExpanded)
          _controller.forward();
        else
          _controller.reverse().then<void>((Null value) {
            setState(() {
              // Rebuild without widget.children.
            });
          });
        PageStorage.of(context)?.writeState(context, _isExpanded);
      });
      if (widget.onExpansionChanged != null) {
        widget.onExpansionChanged(_isExpanded);
      }
    }
  }

  Widget _buildChildren(BuildContext context, Widget child) {
    final Color borderSideColor =
        _borderColor.evaluate(_easeOutAnimation) ?? Colors.transparent;
    final Color titleColor = _headerColor.evaluate(_easeInAnimation);

    return new Container(
      decoration: new BoxDecoration(
          color: _backgroundColor.evaluate(_easeOutAnimation) ??
              Colors.transparent,
          border: new Border(
            top: new BorderSide(color: borderSideColor),
            bottom: new BorderSide(color: borderSideColor),
          )),
      child: new Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          IconTheme.merge(
            data:
                new IconThemeData(color: _iconColor.evaluate(_easeInAnimation)),
            child: new ListTile(
              onTap: toggle,
              leading: widget.leading,
              title: new DefaultTextStyle(
                style: Theme
                    .of(context)
                    .textTheme
                    .subhead
                    .copyWith(color: titleColor),
                child: widget.title,
              ),
              trailing: widget.trailing ??
                  new RotationTransition(
                    turns: _iconTurns,
                    child: const Icon(Icons.expand_more),
                  ),
            ),
          ),
          new ClipRect(
            child: new Align(
              heightFactor: _easeInAnimation.value,
              child: child,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    _borderColor.end = theme.dividerColor;
    _headerColor
      ..begin = theme.textTheme.subhead.color
      ..end = theme.accentColor;
    _iconColor
      ..begin = theme.unselectedWidgetColor
      ..end = theme.accentColor;
    _backgroundColor.end = widget.backgroundColor;

    final bool closed = !_isExpanded && _controller.isDismissed;
    return new AnimatedBuilder(
      animation: _controller.view,
      builder: _buildChildren,
      child: closed ? null : new Column(children: widget.children),
    );
  }
}

可能是Flutter - 选择项目后折叠ExpansionTile的重复问题。 - Yamin
点赞 https://github.com/flutter/flutter/issues/7024 - Günter Zöchbauer
@alex blaze,你在使用扩展瓷砖时找到解决方案了吗? - praveen Dp
@praveenDp,你也可以尝试使用全局键。 - Rishabh
这是我在Bottom Sheet中运行的唯一解决方案:https://dev59.com/jVUM5IYBdhLWcg3wYvXl#65857450 - Sneha Mudhigonda
显示剩余2条评论
4个回答

16

您可以使用ExpandablePanelList来实现展开和折叠视图。使用expansionCallback来维护活动状态以执行展开或折叠。

这里是一个工作示例

class TestExpandableView extends StatefulWidget {
  @override
  _TestExpandableViewState createState() => _TestExpandableViewState();
}

class _TestExpandableViewState extends State<TestExpandableView> {
  int _activeMeterIndex;
  @override
  Widget build(BuildContext context) {
    return Container(
      child: new ListView.builder(
          itemCount:  2,
          itemBuilder: (BuildContext context, int i) {
            return Card(
              margin:
              const EdgeInsets.fromLTRB(10.0, 15.0, 10.0, 0.0),
              child: new ExpansionPanelList(
                expansionCallback: (int index, bool status) {
                  setState(() {
                    _activeMeterIndex = _activeMeterIndex == i ? null : i;
                  });
                },
                children: [
                  new ExpansionPanel(
                      isExpanded: _activeMeterIndex == i,
                      headerBuilder: (BuildContext context,
                          bool isExpanded) =>
                      new Container(
                          padding:
                          const EdgeInsets.only(left: 15.0),
                          alignment: Alignment.centerLeft,
                          child: new Text(
                            'list-$i',
                          )),
                      body: new Container(child: new Text('content-$i'),),),
                ],
              ),
            );
          }),
    );
  }
}

1
你是否也注意到每个ExpansionPanel在展开时顶部有额外的边距?我们能否去掉它? - Samarth Agarwal
如何克服扩展时的额外边距? - Ameer
只需将卡片转换为容器。 - Zhangir Siranov
而不是在“expansionCallback”中维护活动状态,您可以使用“ExpansionPanelList.radio”,它接受一个“ExpansionPanelRadio”列表作为其子项。这将帮助您自动维护活动状态。请参阅 Flutter文档以获取示例用法 - Hafiz

4
ExpansionPanelList.radio是一个小部件,它接受ExpansionPanelRadio的列表作为其子项。与@Aravindh Kumar所做的一样,你不必在expansionCallback中维护活动状态,该小部件允许列表中最多打开一个面板,并自动为您维护活动状态。
请参考flutter文档以获取示例用法
// Flutter code sample for ExpansionPanelList.radio

// Here is a simple example of how to implement ExpansionPanelList.radio.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: MyStatefulWidget(),
      ),
    );
  }
}

// stores ExpansionPanel state information
class Item {
  Item({
    this.id,
    this.expandedValue,
    this.headerValue,
  });

  int id;
  String expandedValue;
  String headerValue;
}

List<Item> generateItems(int numberOfItems) {
  return List.generate(numberOfItems, (int index) {
    return Item(
      id: index,
      headerValue: 'Panel $index',
      expandedValue: 'This is item number $index',
    );
  });
}

class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  List<Item> _data = generateItems(8);

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        child: _buildPanel(),
      ),
    );
  }

  Widget _buildPanel() {
    return ExpansionPanelList.radio(
      initialOpenPanelValue: 2,
      children: _data.map<ExpansionPanelRadio>((Item item) {
        return ExpansionPanelRadio(
            value: item.id,
            headerBuilder: (BuildContext context, bool isExpanded) {
              return ListTile(
                title: Text(item.headerValue),
              );
            },
            body: ListTile(
                title: Text(item.expandedValue),
                subtitle: Text('To delete this panel, tap the trash can icon'),
                trailing: Icon(Icons.delete),
                onTap: () {
                  setState(() {
                    _data.removeWhere((currentItem) => item == currentItem);
                  });
                }));
      }).toList(),
    );
  }
}

0

-2
我认为你需要单独跟踪每个扩展块的展开状态。类似这样的东西:
Map<String, bool> expansionState = Map();

在初始化时,您需要指定键和相关扩展瓷砖是否显示为打开或关闭状态。在我的代码中,我有一个用于扩展瓷砖名称的列表。页面加载时,我执行以下操作:

categoryList.forEach((name) {
   expansionState.putIfAbsent(name, () => true);
});

然后构建器只需引用 expansionState:

Widget _buildCategory(String name, List<OrderItem> children) {
    return ExpansionTile(
      key: PageStorageKey<String>(name),
      initiallyExpanded: expansionState[name], // true,
      title: RichText(
          text: TextSpan(
        text: name,
        style: TextStyle(
            color: Colors.blue[800], fontSize: 16, fontWeight: FontWeight.bold),
        children: <TextSpan>[
          TextSpan(
              text: ' - ' + children.length.toString() + ' items',
              style: TextStyle(
                  color: Colors.grey[800],
                  fontSize: 16,
                  fontWeight: FontWeight.normal)),
        ],
      )),
      onExpansionChanged: ((newState) {
        print(name + ' is now ' + newState.toString());
        expansionState[name] = newState;
      }),
      children: children.map<Widget>(_buildChild).toList(),
    );
  }

此时,您可以添加一个按钮,其onPressed()方法可以在setState()调用中以任何您想要的方式操作expansionState映射。您可以打开它们所有,关闭它们所有,切换它们当前的状态等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接