Flutter避免在折叠/展开ExpansionPanelList

时间:2019-08-30 13:28:15

标签: flutter dart state-management

ExpansionPanelList中,我在扩展/折叠小部件时遇到了重建小部件的问题。

问题在这里:

expansionCallback: (int index, bool isExpanded) {
  setState(() {
    _profileExpansionStateMap[_profileExpansionStateMap.keys.toList()[index]] = !isExpanded;
  });
},

我将其更改为使用Bloc状态管理来解决,但这与setState()具有相同的行为。有什么办法可以避免重建小部件树?我不能使用Selector小部件,因为我认为这不会对我有帮助。

import 'package:flutter/material.dart';
void main()=>runApp(MaterialApp(home: Home(),));

class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() =>HomeState();

}

class HomeState extends State<Home> {
  Map<String, bool> _profileExpansionStateMap = Map<String, bool>();

  @override
  void initState() {
    super.initState();
    _profileExpansionStateMap = {
      "UserInformation": false,
      "UserWeight": false,
      "UserGeneralInformation": false,
    };
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title:Text('ExpansionPanel')),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.all(20.0),
          child:ExpansionPanelList(
            expansionCallback: (int index, bool isExpanded) {
              setState(() {
                _profileExpansionStateMap[_profileExpansionStateMap.keys.toList()[index]] = !isExpanded;
              });
            },
            children: <ExpansionPanel>[
              ExpansionPanel(
                  headerBuilder: (BuildContext context, bool isExpanded) {
                    return Container(
                      height: 80.0,
                      child: Text('aaaaaaaa'),
                    );
                  },
                  body: Container(child:Text('aaaaaaaa')),
                  isExpanded: _profileExpansionStateMap["UserInformation"]),
              ExpansionPanel(
                  headerBuilder: (BuildContext context, bool isExpanded) {
                    return Container(
                      height: 80.0,
                      child: Text('bbbbbbbbbbbb'),
                    );
                  },
                  body: Container(child:Text('bbbbbbbbbbbb')),
                  isExpanded: _profileExpansionStateMap["UserWeight"]),
              ExpansionPanel(
                  headerBuilder: (BuildContext context, bool isExpanded) {
                    return Container(
                      height: 80.0,
                      child: Text('ccccccccc'),
                    );
                  },
                  body: Container(child:Text('ccccccccc')),
                  isExpanded: _profileExpansionStateMap["UserGeneralInformation"]),
            ],
          )
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:2)

ExpansionPanelList.expansionCallback(...)是一种方法,只要您点击ExpansionPanelList内的箭头按钮以展开/折叠它,该方法就会被调用。

在这种方法中,您实际上应该设置传递给bool的{​​{1}}的{​​{1}}值,因此需要您调用isExpanded

但是,如果您对此有疑问,则表明您的代码有问题。因此,无需避免重建小部件状态。