【问题标题】:Using Stream Building with a specific Firestore document将 Stream Building 与特定的 Firestore 文档一起使用
【发布时间】:2018-11-20 03:53:28
【问题描述】:

我正在构建一个 Flutter 应用程序,但我无法理解如何实现 Firestore。在我看过的教程中,我只看到了如何创建整个集合的快照,但是在我的例子中,我的集合是用户,所以我只需要对特定用户的文档进行快照。 Firebase 文档上似乎没有关于如何执行此操作的文档,FlutterFire GitHub 页面上也没有太多文档。请帮忙!

这是我尝试使用 StreamBuilder 构建的小部件。

  @override
  Widget build(BuildContext context) {
    return new StreamBuilder(
      stream: Firestore.instance.collection('users').document(userId).snapshots(),
      builder: (context, snapshot) {
        return new ListView.builder(
          itemCount: //what do I put here?,
          itemBuilder: (context, index) => new Item(//And here?),
        );
      }
    );
  }

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    假设您想使用文档中的 name 参数创建一个 Text

    Widget build(BuildContext context) {
      String userId = "skdjfkasjdkfja";
      return StreamBuilder(
          stream: Firestore.instance.collection('users').document(userId).snapshots(),
          builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (!snapshot.hasData) {
              return Text("Loading");
            }
            var userDocument = snapshot.data;
            return Text(userDocument["name"]);
          }
      );
    }
    

    这只是一个例子。每次更改文档本身时,在文档上创建 StreamBuilder 都会自行重建。您可以尝试此代码,然后转到控制台并更改“名称”值。您的应用将自动反映更改。

    您可以构建使用流中数据的整棵树,而不仅仅是一个 Text

    如果您只想获取文档的当前值,可以通过解析文档引用上的 Futureget() 方法来实现。

    var document = await Firestore.instance.collection('users').document(userId).get(),
    

    【讨论】:

    • 我在尝试构建流时收到此错误:The argument type 'Stream&lt;DocumentSnapshot&gt;' can't be assigned to the parameter type 'Stream&lt;QuerySnapshot&gt;'. 有什么想法吗?
    • @ThéoChampion 你解决了吗?我也面临同样的问题。
    • 我猜该 api 已更改。我可以看看
    • @Tree 你的代码会产生这个错误The argument type 'Stream&lt;DocumentSnapshot&gt;' can't be assigned to the parameter type 'Stream&lt;QuerySnapshot&gt;'
    【解决方案2】:

    每个元素都应该被强制转换,以便在代码后面有一个引用。

      return new StreamBuilder<DocumentSnapshot>(
          stream: Firestore.instance.collection('users').document(userId).snapshots(), //returns a Stream<DocumentSnapshot>
          builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (!snapshot.hasData) {
              return new Text("Loading");
            }
            var userDocument = snapshot.data;
            return new Text(userDocument["name"]);
          }
      );
    }
    

    【讨论】:

    • userDocument 在您使用snapshot.data 时不是映射。所以你会得到NoSuchMethodError: The method '[]' was called on null.
    • 根据问题将您的答案翻译成英文。
    猜你喜欢
    • 1970-01-01
    • 2021-01-11
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 2018-03-20
    • 1970-01-01
    相关资源
    最近更新 更多