Firebase Documentsnapshot映射到Flutter中的Json对象

时间:2019-12-12 00:02:44

标签: firebase flutter google-cloud-firestore jsonserializer

我试图将DocumentSnap从Firebase映射到Flutter中的Json类。我可以确认我正在从文档中获取数据,但是无法将收集到的数据传递给我的Json对象。我已附上代码和错误消息。

用于从Firebase获取文档的类 DatabaseService.dart

Header set Access-Control-Allow-Methods: "GET, POST, OPTIONS"
Header set Access-Control-Allow-Credentials: true
Header set Cache-Control: no-cache
Header set Access-Control-Expose-Headers: "Content-Length"
Header set Access-Control-Allow-Headers: "*"
# Header set Access-Control-Allow-Headers: "Authorization, Origin, Content-Type, Accept, X-Auth-Token"
Header set WWW-Authenticate: "Basic realm='Client Only'"
Header set Access-Control-Allow-Origin: http://dev.qwikfoto.com
Header set Vary: Origin
Header set Access-Control-Max-Age: 84600

Json对象类

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 [];
  }
}

错误消息

编译器消息: lib / widgets / database_service.dart:17:76:错误:参数类型'String'无法分配给参数类型'Map'。  -“地图”来自“ dart:core”。       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')这是我试图获取的文档

2 个答案:

答案 0 :(得分:1)

假设您的集合名称为“ tblcustomers”,

Stream<QuerySnapshot> stream = _db.collection("tblcustomers").snapshots();
  jsonObject = Customers(error: false, errorCode: 0, Items: List<Customers_items>());
  stream.forEach((QuerySnapshot element) {
    if (element == null) return;

    setState(() {
      jsonObject.Items = element.documents.map((e) => Customers_items.fromJson(e.data)).toList();
    });
  });

答案 1 :(得分:0)

您在地图上设置的目标类型必须是地图结果所需的类型。

应该是

querySnapshot.data.map((json)=> UserCheck.fromJson(json))。toList();