You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter抽屉中ExpansionTile子项无法正常加载问题求助

解决Flutter Drawer中ExpansionTile子项无法正确显示的问题

你的核心问题是没有遍历当前分组的所有子数据,还错误复用了外层ListView的索引去取子项,导致子项只显示单个且内容错误。下面是修正后的代码:

修正后的Widget代码

ListView.builder(
  key: Key('builder ${selected.toString()}'),
  padding: const EdgeInsets.only(left: 13.0, right: 13.0, bottom: 25.0),
  shrinkWrap: true,
  physics: const NeverScrollableScrollPhysics(),
  itemCount: dataList.length,
  itemBuilder: (context, index) {
    // 取出当前分组的子列表
    List<Map<String, dynamic>> childrenList = List.from(dataList[index]['children']);
    return ExpansionTile(
      key: Key(index.toString()),
      initiallyExpanded: index == selected,
      trailing: const SizedBox(),
      leading: Icon(
        dataList[index]['icon'],
        color: index == selected ? Colors.black : Colors.grey,
      ),
      title: Text(
        dataList[index]['title'],
        style: TextStyle(
          color: index == selected ? Colors.black : Colors.grey,
          fontSize: 17.0,
          fontWeight: FontWeight.bold,
        ),
      ),
      onExpansionChanged: (newState) {
        setState(() {
          selected = newState ? index : -1;
        });
      },
      // 遍历子列表生成所有子项
      children: childrenList.map((child) {
        return Padding(
          padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 12.0),
          child: Text(
            child['title'],
            style: TextStyle(
              color: index == selected ? Colors.red : Colors.grey,
            ),
          ),
        );
      }).toList(),
    );
  },
)

关键修改点

  1. 遍历子数据:用map方法遍历当前分组的children列表,为每个子项生成对应的Text组件,再转成List作为ExpansionTile的children。
  2. 修正索引错误:不再使用外层的index访问子列表,而是直接用遍历得到的child对象获取标题,避免索引不匹配的问题。
  3. 优化内边距:把原来的EdgeInsets.all(25.0)改成对称内边距,让子项排版更合理。

如果子项数量较多,也可以改用ListView.builder作为ExpansionTile的children(记得设置shrinkWrap: true和physics: NeverScrollableScrollPhysics()),避免性能问题:

children: [
  ListView.builder(
    shrinkWrap: true,
    physics: const NeverScrollableScrollPhysics(),
    itemCount: childrenList.length,
    itemBuilder: (context, childIndex) {
      return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 12.0),
        child: Text(
          childrenList[childIndex]['title'],
          style: TextStyle(
            color: index == selected ? Colors.red : Colors.grey,
          ),
        ),
      );
    },
  )
]

内容的提问来源于stack exchange,提问作者Ravindra S. Patil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:16:06