Flutter:滚动时ExpansionTile强制关闭

3

当ExpansionTile探测到滚动行为时,例如我立即滚动页面时,它会强制关闭...我想保持ExpansionTile打开状态,直到我点击其标题。

可能的原因是什么?

expansionTile force loses


请查看此链接 https://dev59.com/bWkMtIcB2Jgan1znSSBw#71556257 - Ketan Ramani
2个回答

1
你的ExpansionTile立即关闭的原因是,当你滚动listview时,特别是使用ListView.builder创建的列表会被重新构建,因此,如果你想保留某个ExpansionTile的状态,你应该在build函数之外保存其状态值,并使用initiallyExpanded属性:
   List<bool> status = <bool>[] ; //store the statuses of your tiles here

   ExpansionTile(
    title: Text('Item'),
    backgroundColor: Colors.transparent,
    initiallyExpanded: status[index],
   ),

1

使用onExpansionChanged回调函数从列表中添加和删除索引,并在包含该索引时设置initiallyExpanded

class _WidgetState extends State<Widget> {
    
      List expandedIndices = [];
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
           body: ListView.builder(
                    physics: const BouncingScrollPhysics(
                    parent: AlwaysScrollableScrollPhysics()),
                    itemCount: 10,
                    itemBuilder: (BuildContext context, int index) {
                        return ExpansionTile(
                            title: Text('Item'),
                             onExpansionChanged: (expanded) {
                                 if(expanded) {
                                     expandedIndices.add(index);
                                 }
                                 else{
                                     expandedIndices.remove(index);
                                 }
                             },
                             initiallyExpanded: expandedIndices.contains(index),);
                    } 
                )
            );
       }
  }

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