简体   繁体   中英

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.

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

A value of type 'User' can't be returned from method 'getUser' because it has a return type of 'User'. dart(return_of_invalid_type)

Imports are correct, the User object are the same, what am I doing wrong?

The method has an async modifier so it should return a Future which in this case should be a Future.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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