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赋值阶段就已经产生,运行到元素访问时已经是类型异常的列表了。
修复步骤
- 修正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(); } }
- 额外补充:你当前代码在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
相关产品推荐
相关产品推荐

