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

Flutter递归Widget实现树视图时List<dynamic>转Map列表类型报错

问题原因
  • 你出错的根源不在el[i]的转换,而在el变量定义时的强制转换:Firestore返回的嵌套列表默认是List<dynamic>类型,Dart不支持直接将List<dynamic>整体强转为List<Map<String, dynamic>>,你写的widget.elements["children"] as List<Map<String, dynamic>>在运行时只会验证外层是List类型,不会验证内部元素类型,这个隐患会在你访问列表元素时触发类型不匹配错误。
  • 你尝试单独强转el[i]不生效,是因为错误在el赋值阶段就已经产生,运行到元素访问时已经是类型异常的列表了。
修复步骤
  1. 修正children字段的类型转换逻辑,不要直接整体强转,推荐两种写法:
    写法1:用cast方法做泛型转换,适合确定children内所有元素都是Map<String,dynamic>的场景
// 替换原来的el变量定义行
List<Map<String, dynamic>> el = [];
if (widget.elements.containsKey("children")) {
  final childrenRaw = widget.elements["children"];
  if (childrenRaw is List) {
    el = childrenRaw.cast<Map<String, dynamic>>();
  }
}

写法2:逐个过滤合法元素,容错性更高,避免个别异常元素导致整个列表崩溃

List<Map<String, dynamic>> el = [];
if (widget.elements.containsKey("children")) {
  final childrenRaw = widget.elements["children"];
  if (childrenRaw is List) {
    el = childrenRaw.whereType<Map<String, dynamic>>().toList();
  }
}
  1. 额外补充:你当前代码在ListView内部嵌套了子ListView,没有设置滚动约束会触发布局溢出错误,给Levels组件内的ListView加上两个属性即可:
child: ListView(
  // 新增下面两行
  shrinkWrap: true,
  physics: const NeverScrollableScrollPhysics(),
  children: [
    Text(widget.elements["name"] ?? ""),
    Text(widget.elements["total"]?.toString() ?? "0.0"),
    for (int i = 0; i< el.length;i++) Levels(elements:el[i], level: widget.level+1) 
  ]
)

内容的提问来源于stack exchange,提问作者Mind84

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:15:01