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

Flutter从Firestore取数据时出现_List<dynamic>不是String子类型错误

问题解决方法

这个_TypeError (type 'List<dynamic>' is not a subtype of type 'String')报错的核心原因是:代码中某一处逻辑预期接收String类型的值,但实际传入了List<dynamic>类型数据,结合你提供的代码,按以下步骤排查修复:

排查步骤

  • 第一步:检查SaveLocationIndex action的payload参数类型定义
    你当前代码中将List类型的temp变量作为payload传入,如果SaveLocationIndex的payload被声明为String类型,就会直接触发该报错,将payload类型修改为匹配的List类型即可,例如如果存储的是字符串格式的地点列表,可声明为List<String>。
  • 第二步:检查AppState中存储locationIndex的对应字段类型
    如果你在AppState中声明该字段为String类型,dispatch之后存入状态时也会触发该报错,同步修改为对应List类型即可。
  • 第三步:优化Firestore取值的类型校验逻辑
    你当前直接将Firestore返回的dynamic类型数据强转成List,没有做类型校验,字段不存在或者类型不匹配时也容易触发类型异常,建议补充校验逻辑。

修复后参考代码

class ActfMiddleWare {
  ///Fetches LocationData From Firestore and Save it in Store;
  locationIndexMiddleware() {
    return (Store<AppState> store, action, NextDispatcher next) async {
      if (action is GetLocationIndex) {
        final docSnapshot = await FirebaseFirestore.instance
            .collection('locations')
            .doc('locationIndex')
            .get();

        if (docSnapshot.exists) {
          final data = docSnapshot.data()!;
          // 先校验字段类型
          if (data['locations'] is List) {
            // 按需转换为具体的List类型,比如List<String>就用.cast<String>()
            List temp = (data['locations'] as List).cast<String>();
            store.dispatch(SaveLocationIndex(payload: temp));
          }
        }
      }
      next(action);
    };
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 01:48:00