Firebase Documentsnapshot映射到Flutter中的Json对象

问题描述 投票:0回答:1

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

用于从Firebase获取文档的类DatabaseService.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:错误:参数类型'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));

firebase结构enter image description here^collection('users')。document('user.uid')这是我试图获取的文档

firebase flutter google-cloud-firestore jsonserializer
1个回答
0
投票

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

应该是

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

© www.soinside.com 2019 - 2024. All rights reserved.