aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
防止Bad state: No element异常,当你的列表为空时,可以处理列表没有元素的情况。具体来说,删除所有元素后,您可以检查列表是否为空,并有条件地在 ExpansionTile 内显示不同的小部件(例如占位符或空状态消息)。以下是修改代码的方法:
class GroupsNew extends StatefulWidget {
const GroupsNew({super.key});
@override
State<GroupsNew> createState() => _GroupsNewState();
}
class _GroupsNewState extends State<GroupsNew> {
bool _customIcon = false;
List<String> test = ["string"];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Groups')),
body: Padding(
padding: const EdgeInsets.all(14.0),
child: ExpansionTile(
title: Text('Expandable List'),
trailing: Icon(_customIcon ? Icons.expand_less : Icons.expand_more),
onExpansionChanged: (bool expanded) {
setState(() => _customIcon = expanded);
},
children: test.isNotEmpty
? test
.map((item) => ListTile(
title: Text(item, style: TextStyle(fontSize: 20)),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
setState(() {
test.remove(item);
});
},
),
))
.toList()
: [
ListTile(
title: Text(
'No items available',
style: TextStyle(fontSize: 16, fontStyle: FontStyle.italic),
),
),
],
),
),
);
}
}