颤动 - 选择项目后折叠ExpansionTile

问题描述 投票:6回答:4

我选择一个项目后,我试图让ExpansionTile崩溃,但它没有关闭打开的列表。

我试图使用onExpansionChanged属性,但我没有成功

你怎么能解决这个问题?

插入一个gif,证明ExpansionTile在选择项目后不会崩溃,下面也是使用的代码。

enter image description here

import 'package:flutter/material.dart';

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

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

class ExpansionTileSampleState extends State<ExpansionTileSample> {
  String foos = 'One';

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('ExpansionTile'),
        ),
        body: new ExpansionTile(
          title: new Text(this.foos),
          backgroundColor: Theme.of(context).accentColor.withOpacity(0.025),
          children: <Widget>[
            new ListTile(
              title: const Text('One'),
              onTap: () {
                setState(() {
                  this.foos = 'One';
                });
              },              
            ),
            new ListTile(
              title: const Text('Two'),
              onTap: () {
                setState(() {
                  this.foos = 'Two';
                });
              },              
            ),
            new ListTile(
              title: const Text('Three'),
              onTap: () {
                setState(() {
                  this.foos = 'Three';
                });
              },              
            ),
          ]
        ),
      ),
    );
  }
}
dart flutter
4个回答
13
投票

这是一个解决方案。我们只需在expand中添加collapsetoggleExpansionTile功能。

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: new AppExpansionTile(
                    key: expansionTile,
                    title: new Text(this.foos),
                    backgroundColor: Theme
                        .of(context)
                        .accentColor
                        .withOpacity(0.025),
                    children: <Widget>[
                        new ListTile(
                            title: const Text('One'),
                            onTap: () {
                                setState(() {
                                    this.foos = 'One';
                                    expansionTile.currentState.collapse();
                                });
                            },
                        ),
                        new ListTile(
                            title: const Text('Two'),
                            onTap: () {
                                setState(() {
                                    this.foos = 'Two';
                                    expansionTile.currentState.collapse();
                                });
                            },
                        ),
                        new ListTile(
                            title: const Text('Three'),
                            onTap: () {
                                setState(() {
                                    this.foos = 'Three';
                                    expansionTile.currentState.collapse();
                                });
                            },
                        ),
                    ]
                ),
            ),
        );
    }
}

// --- 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),
        );
    }
}

3
投票

下面的解决方案可行,但它非常hacky,可能不是最好的:



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

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

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

    class ExpansionTileSampleState extends State {
      String foos = 'One';
      int _key;

      _collapse() {
        int newKey;
        do {
          _key = new Random().nextInt(10000);
        } while(newKey == _key);
      }

      @override
      void initState() {
        super.initState();
        _collapse();
      }

      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          home: new Scaffold(
            appBar: new AppBar(
              title: const Text('ExpansionTile'),
            ),
            body: new ExpansionTile(
                key: new Key(_key.toString()),
                initiallyExpanded: false,
                title: new Text(this.foos),
                backgroundColor: Theme
                    .of(context)
                    .accentColor
                    .withOpacity(0.025),
                children: [
                  new ListTile(
                    title: const Text('One'),
                    onTap: () {
                      setState(() {
                        this.foos = 'One';
                        _collapse();
                      });
                    },
                  ),
                  new ListTile(
                    title: const Text('Two'),
                    onTap: () {
                      setState(() {
                        this.foos = 'Two';
                        _collapse();
                      });
                    },
                  ),
                  new ListTile(
                    title: const Text('Three'),
                    onTap: () {
                      setState(() {
                        this.foos = 'Three';
                        _collapse();
                      });
                    },
                  ),
                ]
            ),
          ),
        );
      }
    }

我发现ExpansionTile具有initialExpanded属性,这是使其崩溃的唯一方法。由于属性最初只能在每次调用构建时重新创建ExpansionTile。要强制它,您只需在每次构建时分配不同的密钥。这可能不是性能最佳的解决方案,但ExpansionTile非常简单,所以这应该不是问题。


0
投票

我做了一个TreeView小部件。它使用ExpansionTile来模拟层次结构。每个ExpansionTile都可以托管一个可以托管等的ExpansionTile集合。

一切正常,直到我想添加2个功能:全部展开/全部折叠。帮助我克服这个问题的是GlobalKey。

我的TreeView小部件托管在页面中,并与全局密钥一起使用。我暴露了一个VoidCallback。该实现在setState方法中设置了一个新键。

// TreeView host page
GlobalKey<TreeViewState> _key = GlobalKey();
void redrawWidgetCallback() {
    setState(() {
      // Triggers a rebuild of the whole TreeView.
      _key = GlobalKey();
    });
}
[...]
// In the Scaffold body :
TreeView(
    key: _key,
    treeViewItems: widget.treeViewItems,
    redrawWidgetCallback: redrawWidgetCallback,
  )

然后在我的小部件中的collapse / expand方法中,最后,我调用了widget.redrawWidgetCallback。无需处理treeView的每个级别的键:根元素小部件就足够了。

它可能有性能问题/不是正确的方法。但是由于我的TreeView将不会使用超过50个节点,所以在我找到一个更好的解决方案而不涉及创建ExpandableTile之前我可以使用,因为我相信这种行为将在ExpansionTile本身上提供。

PS:请注意,此变通方法不会运行展开动画。


0
投票

从ExpansionTile类创建一个克隆,并用以下代码替换构建方法代码:

@override
Widget build(BuildContext context) {
  final bool closed = !_isExpanded && _controller.isDismissed;
  return AnimatedBuilder(
    animation: _controller.view,
    builder: _buildChildren,
    child: closed ? null : GestureDetector(
      child: Column(children: widget.children),
      onTap: _handleTap,
    ),
  );
}

点击每个项目后,ExpansionTile将崩溃。

注意:如果其中一个孩子有onTap回拨,则此解决方案不起作用。在这种情况下,您必须提供onChildTap处理程序以在用例中传递tapped child的索引。(联系我获取完整代码)


0
投票

我找到了一个简单的解决方只需向ExpansionTile小部件添加一个全局密钥,它就可以按预期工作。

ExpansionTile(
  key: GlobalKey(),
  title: Text(title),
  children: listTiles,
  ...
)

不知道为什么会这样,但我的猜测是,每次添加一个键都会强制ExpansionTile小部件在每次在setState中更改标题时重建,因此返回其初始(折叠)状态。

© www.soinside.com 2019 - 2024. All rights reserved.