【问题标题】:How to store data into model using fromJson in flutter firebase?如何在flutter firebase中使用fromJson将数据存储到模型中?
【发布时间】:2021-09-21 16:29:13
【问题描述】:

目前我正在做一个颤振项目。我正在尝试创建一个从 Firebase 文档获取快照并使用 fromJson 函数将其存储到 userData 模型中的函数。

这是我的 User.dart

class UserData {
  // final String uid;
  final String usn;
  final String fullName;
  final int? sem;
  final String branch;
  final String section;

  UserData({
    required this.usn,
    required this.fullName,
    required this.sem,
    required this.branch,
    required this.section,
  });

  factory UserData.fromJson(Map<String, dynamic> json) {
    return UserData(
        usn: json['usn'],
        fullName: json['fullName'],
        sem: json['sem'],
        branch: json['branch'],
        section: json['section']);
  }

  Map<String, dynamic> toMap() {
    return {
      'usn': usn,
      'fullName': fullName,
      'sem': sem,
      'branch': branch,
      'section': section
    };
  }
}

在我的 database.dart 我想在其中创建一个 Stream 函数以映射到 fromJson 这是我尝试过的

 Stream<UserData?> curUserData() {
    return _db.collection('users').doc(user.uid).snapshots()
    .map((DocumentSnapshot snapshot) => UserData.fromJson(snapshot.data()));
  }

谁能改正这个功能?

上面的函数出错了。

【问题讨论】:

  • 错误是什么?如果您显示错误,则可能更容易找到并解决问题
  • 错误:参数类型“对象?”不能分配给参数类型'Map'。

标签: firebase flutter dart firebase-realtime-database google-cloud-firestore


【解决方案1】:

您的问题只是错误的类型断言。尝试这个: 将DocumentSnapshot 更改为DocumentSnapshot&lt;Map&lt;String, dynamic&gt;&gt;

 Stream<UserData?> curUserData() {
    return _db.collection('users').doc(user.uid).snapshots()
    .map((DocumentSnapshot<Map<String, dynamic>> snapshot) => UserData.fromDocument(snapshot.data()!));
  }

【讨论】:

  • 我不能在课堂上或我的 database.dart 中使用 DocumentSnapshot>,我需要从 firestore 实时更新,我需要使用 Stream
  • 我编辑了答案,因为我忘了编辑代码。如果它不起作用,其他答案可能对您有用。
  • 参数类型'Map?'不能分配给参数类型“Map”。我仍然收到错误。
  • 只需在snapshot.data() 之后添加一个! 符号:snapshot.data()!
  • 太棒了,非常感谢你们@NelsomThiago 和@Jomon 帮助我,在@Nelson 的答案中添加正确的标记,@Nelson 可以编辑代码并添加@987654327 @你的答案?。
猜你喜欢
  • 2021-08-31
  • 2020-03-22
  • 2021-09-27
  • 2021-07-22
  • 2020-04-13
  • 2020-05-25
  • 2019-12-14
  • 2021-10-09
  • 2021-07-14
相关资源
最近更新 更多