【发布时间】:2020-04-05 07:57:22
【问题描述】:
我正在尝试将 DocumentSnap 从 Firebase 映射到 Flutter 中的 Json 类。我可以确认我正在从文档中获取数据,但我无法将收集到的数据传递给我的 Json 对象。我附上了代码和错误信息。
从 Firebase 获取文档的类 数据库服务.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:oast_app/widgets/auth_class.dart';
class FireTest {
Future<List<UserCheck>> streamUser(FirebaseUser user) async {
DocumentSnapshot querySnapshot =
await Firestore.instance.collection('users').document(user.uid).get();
if (querySnapshot.exists) {
print('success');
print(querySnapshot.data['fname']);
print(querySnapshot.data['lname']);
querySnapshot.data.map<String, dynamic>((json) => UserCheck.fromJson(json)); **this is whats erroring**
}
return [];
}
}
Json 对象类
import 'package:flutter/material.dart';
import 'package:json_annotation/json_annotation.dart';
part 'auth_class.g.dart';
@JsonSerializable(nullable: false)
class UserCheck extends ChangeNotifier {
final String uid;
final String fName;
final String lName;
final String regEmail;
final String org;
UserCheck({
this.uid,
this.fName,
this.lName,
this.regEmail,
this.org,
});
factory UserCheck.fromJson(Map<String, dynamic> json) =>
_$UserCheckFromJson(json);
Map<String, dynamic> toJson() => _$UserCheckToJson(this);
}
错误信息
编译器消息: lib/widgets/database_service.dart:17:76:错误:参数类型“字符串”不能分配给参数类型“地图”。 - “地图”来自“飞镖:核心”。 querySnapshot.data.map((json) => UserCheck.fromJson(json)); ^ lib/widgets/database_service.dart:17:67:错误:“UserCheck”类型的值不能分配给“MapEntry”类型的变量。 - 'UserCheck' 来自'package:oast_app/widgets/auth_class.dart' ('lib/widgets/auth_class.dart')。 - 'MapEntry' 来自'dart:core'。 querySnapshot.data.map((json) => UserCheck.fromJson(json)); ^ lib/widgets/database_service.dart:17:47:错误:无法将参数类型“MapEntry Function(String)”分配给参数类型“MapEntry Function(String, dynamic)”。 - 'MapEntry' 来自'dart:core'。 querySnapshot.data.map((json) => UserCheck.fromJson(json));
火力基地结构 enter image description here ^ collection('users').document('user.uid') 这是我试图获取的文档
【问题讨论】:
-
你想把documentsnapshot转换成数据类吗?
-
是的,我的 UserCheck 类中有什么用于 Json
-
不要使用地图操作,而是使用'for each'。 querySnapshot.data.forEach((json) => UserCheck.fromJson(json));
-
@Alvindrakes 进行了更改,新错误,编译器消息:lib/widgets/database_service.dart:16:63:错误:无法将参数类型“字符串”分配给参数类型“地图'。 - “地图”来自“飞镖:核心”。 querySnapshot.data.forEach((json) => UserCheck.fromJson(json));
-
您能否使用您的 Firestore 数据结构的屏幕截图来编辑您的问题,这样我们更容易理解传入的数据。
标签: firebase flutter google-cloud-firestore jsonserializer