【问题标题】:Is there a way to get Firestore data to User model class in flutter then pass the data to the screens?有没有办法在 Flutter 中将 Firestore 数据获取到 User 模型类,然后将数据传递到屏幕?
【发布时间】:2021-03-30 08:29:58
【问题描述】:

有没有一种方法可以将 Firestore 数据(例如“用户信息”)放入 Flutter 中的用户模型类中? 这是我的用户类:


class Users {
  final int id;
  final String firstName;
  final String lastName;
  final String emailAddress;
  final String imageProfile;

  const Users({
    this.id,
    this.firstName,
    this.lastName,
    this.emailAddress,
    this.imageProfile,

  });

}

final Users currentUser = Users(
  id: 'GET_DATA_FROM_FIRESTORE'/// firebaseUSer.currentUserUID
  firstName: 'GET_DATA_FROM_FIRESTORE',
  lastName: 'GET_DATA_FROM_FIRESTORE',
  emailAddress: 'GET_DATA_FROM_FIRESTORE',
  imageProfile: 'GET_DATA_FROM_FIRESTORE',
);

然后将带有 currentUser.firstName 等的数据传递给其他小部件。 我需要检索到此类中的数据在颤振中创建为 SignuUp 表单并推送到 Firestore 集合

【问题讨论】:

  • 您似乎尚未尝试查询 Firestore。从使用documentation 开始,然后一旦您从文档中获取数据,就应该清楚如何将其放入数据类中。

标签: flutter google-cloud-firestore


【解决方案1】:

我在我的项目中使用了它。我希望这会有所帮助。

模型类

class Message{
  String id;
  String message;
  String senderId;
  Timestamp timeStamp;
  bool isMedia;
  Message({this.id,this.message,this.senderId,this.timeStamp,this.isMedia});
  factory Message.fromSnapshot(DocumentSnapshot snapshot){
    return Message(
      id:snapshot.id,
      message: snapshot.data()['message'],
      senderId: snapshot.data()['senderId'],
      timeStamp: snapshot.data()['timeStamp'],
      isMedia: snapshot.data()['isMedia'],
    );
  }
  Map<String, dynamic> toJson() =>
  {
    'message': message,
    'senderId': senderId,
    'isMedia': isMedia,
    'timeStamp': DateTime.now(),
  };
}

服务类

*首字母

  final FirebaseFirestore _fBaseFireStore = FirebaseFirestore.instance;
  CollectionReference _collectionRef;
  MessageService() {
    _collectionRef = _fBaseFireStore.collection('Conversation');
  }

*从 Firestore 获取数据

    Stream<List<Message>> getMessages(String conversationId) {
    var ref = _collectionRef
        .doc(conversationId)
        .collection('messages');
    return ref.snapshots().map(
        (event) => event.docs.map((e) => Message.fromSnapshot(e)).toList());
  }

*将数据写入firestore

  Future<void> sendMessage(Message message, String conversationId) async {
    var ref = _collectionRef.doc(conversationId).collection('messages');
    await ref.add(message.toJson());
  }

【讨论】:

  • 非常感谢 _collectionRef 呢?
  • 这是父集合 _fBaseFireStore = FirebaseFirestore.instance; _collectionRef = _fBaseFireStore.collection('Conversation');
  • 您能否也与这位家长一起编辑上面的回复,以便我更好地理解为什么会出现错误?
猜你喜欢
  • 2020-06-16
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 2019-10-27
  • 2021-07-14
  • 2021-06-23
相关资源
最近更新 更多