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

Flutter升级后AsyncSnapshot<Object?>无法赋值给Map<String,dynamic>如何解决

报错根因

两个报错均由Flutter版本升级后空安全类型推断收紧、SQLite查询返回值类型调整共同导致:

  • 未给FutureBuilder指定泛型,编译器无法推断lect.data的实际类型,默认识别为Object?,因此既无法直接传入要求Map<String,dynamic>的fromJson方法,也无法直接使用[]操作符取值
  • 新版本SQLite返回的查询结果类型从Map<String, dynamic>改为Map<String, Object?>,和原fromJson方法的入参类型不匹配

解决方案

方案1:调整fromJson方法适配新类型(推荐)

直接修改工厂方法的入参类型,匹配SQLite新返回值格式:

factory Lecturer.fromJson(Map<String, Object?> json)=>Lecturer(
  name: json['name'] as String,
  email: json['email'] as String,
);

如果数据库字段可能为空,可搭配空判断加默认值避免崩溃:

factory Lecturer.fromJson(Map<String, Object?> json)=>Lecturer(
  name: json['name'] as String? ?? '未知讲师',
  email: json['email'] as String? ?? '无邮箱信息',
);

方案2:仅修改FutureBuilder调用逻辑(无需改动原有fromJson)

给FutureBuilder明确泛型,调用fromJson时对参数做类型转换即可:

FutureBuilder<List<Map<String, Object?>>>(
  future: DB.getLecturer(),
  builder: (_, AsyncSnapshot<List<Map<String, Object?>>> lect){
    if(!lect.hasData){
      return const CircularProgressIndicator();
    }
    // 已判断存在数据,用!做非空断言,再将Map转为dynamic类型传入原有方法
    Lecturer l = Lecturer.fromJson(Map<String, dynamic>.from(lect.data!.first));
    // 后续业务逻辑
    return ...;
  }
),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:45:01