简体   繁体   English

在 Flutter 中从 Firestore 检索和投射单个文档

[英]Retrieving and casting single document from Firestore in Flutter

I'm trying to retrieve a single document from Firestore and transform it into an object of my model.我正在尝试从 Firestore 检索单个文档并将其转换为我的 model 的 object。

Model: Model:

class User {
  final String uid;
  final String email;
  final String nome;
  final String cognome;
  final String displayName;
  final Ruolo ruolo;
  String idSquadra;
  DateTime scadenzaCertificato;

  User(
      {this.uid,
      this.ruolo,
      this.email,
      this.nome,
      this.cognome,
      this.displayName,
      this.idSquadra,
      this.scadenzaCertificato});

  static User fromSnapshot(DocumentSnapshot snapshot) {
    return User(
        uid: snapshot.documentID,
        email: snapshot['email'],
        nome: snapshot['nome'],
        cognome: snapshot['cognome'],
        displayName: snapshot['displayName'],
        ruolo: snapshot['ruolo'],
        idSquadra: snapshot['idSquadra'],
        scadenzaCertificato: snapshot['scadenzaCertificato']);
  }
}

Retrieve:取回:

import 'package:alley_app/model/data.dart';
import 'package:alley_app/model/user.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class DatabaseService {

  final CollectionReference usersCollection = Firestore.instance.collection('users');

  User getUser(String uid) async {
    return User.fromSnapshot(await usersCollection.document(uid).get());
  }
}

The getUser function keeps giving me an error getUser function 一直给我一个错误

A value of type 'User' can't be returned from method 'getUser' because it has a return type of 'User'.无法从方法“getUser”返回“User”类型的值,因为它的返回类型为“User”。 dart(return_of_invalid_type)飞镖(return_of_invalid_type)

Imports are correct, the User object are the same, what am I doing wrong?导入正确,用户 object 相同,我做错了什么?

The method has an async modifier so it should return a Future which in this case should be a Future.该方法有一个async修饰符,因此它应该返回一个 Future,在这种情况下应该是一个 Future。

Future<User> getUser(String uid) async {
  return User.fromSnapshot(await usersCollection.document(uid).get());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM