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

Firebase嵌套JSON调试可见但factory fromJson返回null问题求助

问题原因及修复方案

核心问题

你的GameInfo类构造函数仅声明了入参,没有将入参值绑定到类的实例属性,导致fromJson中正确解析出的字段值传入构造函数后,没有被赋值给实例的对应字段,最终所有字段均为默认的null值。

修复方法

将GameInfo的构造函数修改为直接绑定同名实例属性的写法:

class GameInfo {
  String? title1;
  String? title2;
  String? title3;
  String? desc1;
  String? desc2;
  String? desc3;

  // 修改构造函数,用this.直接绑定入参到同名实例属性
  GameInfo({
    required this.title1,
    required this.title2,
    required this.title3,
    required this.desc1,
    required this.desc2,
    required this.desc3,
  });

  // 其余fromJson等代码保持不变即可
  factory GameInfo.fromJson(Map<String, dynamic> json) {
    return GameInfo(
      title1: json['title1'] == null || json['title1'].isEmpty
          ? null
          : json['title1']['en'] as String,
      title2: json['title2'] == null || json['title2'].isEmpty
          ? null
          : json['title2']['en'] as String,
      title3: json['title3'] == null || json['title3'].isEmpty
          ? null
          : json['title3']['en'] as String,
      desc1: json['text1'] == null || json['text1'].isEmpty
          ? null
          : json['text1']['en'] as String,
      desc2: json['text2'] == null || json['text2'].isEmpty
          ? null
          : json['text2']['en'] as String,
      desc3: json['text3'] == null || json['text3'].isEmpty
          ? null
          : json['text3']['en'] as String,
    );
  }
}

可选排查项

如果修改后仍有问题,可以检查以下两点:

  • 确认Firebase存储的gameInfo下的字段名和代码中读取的字段完全一致,无大小写、拼写偏差
  • 可以在fromJson方法中添加打印逻辑,比如print(json['title1']['en']),确认字段取值环节正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:27:03