Flutter ExpansionTile ListTile 删除元素不良状态:无元素

问题描述 投票:0回答:1

我想显示多个 ListTiles,它们代表 ExpansionTile 中列表之外的元素。 我遇到的问题是,当我删除该特定列表中的所有元素时,我收到错误: 不良状态:无元素异常。 我怎样才能防止这种情况发生?我仍然想保留 ExpansionTile 本身。

enter image description here

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) {
...
body: Padding(
    padding: const EdgeInsets.all(14.0),
    child: ExpansionTile(
    ...
    children: [
        ListTile(
        title: Text(test.first, style: TextStyle(fontSize: 20)),
          trailing: IconButton(
              onPressed: () {
                setState(() {
                  **test.remove(test.first);
                  if (test.length == 0) {
                    /// pls help :D ///**
                  }
                });
              },
             )
        ],
      onExpansionChanged: (bool expanded) {
        setState(() => _customIcon = expanded);
      },
    ),
  ),
);
}
}
flutter listtile expansion-tile
1个回答
0
投票

防止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),
                    ),
                  ),
                ],
        ),
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.