Flutter-尝试在List View Builder中创建扩展面板列表时,展开和折叠功能不起作用。当我在扩展调用中验证索引值时,它始终返回0。因此它无法正确执行,但是我不知道如何解决它。我已经提供了我的大代码库的代码段。
class EventsPage extends StatefulWidget {
@override
_EventsPageState createState() {
return _EventsPageState();
}
}
class _EventsPageState extends State<EventsPage> {
EventsApi _eventsApi = new EventsApi();
Future<List<EventList>> fetchPost;
List<bool> _isExpanded;
@override
void initState() {
// TODO: implement initState
super.initState();
fetchPost = _eventsApi.fetchPost('2017-06-01', '2018-12-10');
}
void expandList(int length) {
_isExpanded = new List(length);
_isExpanded.fillRange(0, length - 1, false);
}
@override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder<List<EventList>>(
future: fetchPost,
builder: (context, snapshot) {
if (snapshot.hasData) {
expandList(snapshot.data.length); //initialize the expand list
return Container(
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ExpansionPanelList(
animationDuration: Duration(milliseconds: 500),
expansionCallback: (int index, bool isExpanded) {
setState(() {});
},
children: <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (context, isExpanded) {
return Text(" my tile number was $index");
},
isExpanded: true,
body: Container(color: Colors.black),
)
],
);
}),
);
}
答案 0 :(得分:0)
您的代码中有一些错误,我已将其修复,这里有一个示例:
class _EventsPageState extends State<EventsPage> {
List<String> fetchPost;
List<bool> _isExpanded;
Future<List<String>> loadData() async {
await Future.delayed(Duration(seconds: 3));
return List.generate(20, (index) => "$index").toList();
}
void expandList(int length) {
if (_isExpanded == null) {
_isExpanded = new List(length);
_isExpanded.fillRange(0, length - 1, false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: FutureBuilder<List<String>>(
future: loadData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
expandList(snapshot.data.length); //initialize the expand list
return SingleChildScrollView(
child: ExpansionPanelList(
animationDuration: Duration(milliseconds: 500),
expansionCallback: (int index, bool isExpanded) {
setState(() {
_isExpanded[index] = !isExpanded;
print("INDEX : $index ... $isExpanded");
});
},
children: buildPanelList(snapshot.data)),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
})),
);
}
List<ExpansionPanel> buildPanelList(List<String> data) {
List<ExpansionPanel> children = List<ExpansionPanel>();
for (int i = 0; i < data.length; i++) {
children.add(ExpansionPanel(
headerBuilder: (context, isExpanded) {
return Text(" my tile number was $i");
},
isExpanded: _isExpanded[i] ?? false,
body: Container(
color: Colors.black,
),
));
}
return children;
}
}