首页 > 解决方案 > Flutter firebase 从文档中获取字段

问题描述

我正在尝试从集合中的字段获取消息。这是一个只读数据,我已经像这样建模了

class SocialShare {
  final String message;
  SocialShare({
    this.message,
  });
  factory SocialShare.fromJson(Map<String, dynamic> json) {
    return SocialShare(
      message: json['message'],
    );
  }
}

我有一个名为“社交分享”的集合,其中包含一个文档,其中包含一个名为 message 的字段。

我是这样称呼它的

class SocialShares {
  final CollectionReference _socialMessage =
      FirebaseFirestore.instance.collection('socialShare');

  Future<SocialShare> fetchsocial() {
    return _socialMessage.get().then((value) {
      return SocialShare.fromJson(value); // how can i call it
    });
  }
}

我如何从 firebase 获得该值

标签: firebaseflutterfirebase-realtime-databasegoogle-cloud-firestore

解决方案


您可以执行 fetchSocial async 并等待结果返回:

fetchSocial() async{
  var value = await _socialMessage.get();
  return SocialShare.fromJson(value);
}

然后你必须用 await 或者你需要的地方调用 fetchSocial 方法。

等待 fetchSocial() 或 fetchSocial.then ...


推荐阅读