【问题标题】:Flutter - Cannot retrieve list of documents in a Firebase collectionFlutter - 无法检索 Firebase 集合中的文档列表
【发布时间】:2020-01-05 22:53:06
【问题描述】:

我正在尝试获取 Firebase 集合中所有文档名称的列表以显示在 DropdownButton 中,为此我创建了一个自定义小部件 _DropdownListWithLabel。我的集合中有两个文档(我可以在 Firebase 控制台中看到这两个文档),但是当我尝试将所有文​​档的名称作为字符串列表检索时,只显示一个。这是执行此操作的代码的 sn-p:

StreamBuilder<QuerySnapshot>(
    stream: Firestore.instance
        .collection('collectionName')
        .snapshots(),
    builder: (context, snapshot) {
        print(
            "Number of documents: ${snapshot.data.documents.length}, 
            ${snapshot.data.documents.first.documentID}");
        return _DropdownWithLabel(
            'Label', 
             snapshot.data.documents.map((doc) => doc.documentID).toList());
    }) //StreamBuilder

作为参考,print 语句显示如下: Number of documents: 1, documentName

为什么这段代码不能从这个集合中检索两个文档名称?

编辑:这是 _DropdownWithLabel 小部件。如果我尝试在 ListView 或包含 Text 小部件列表的列中列出文档名称,我会得到相同的结果,即只显示一个文档名称。

class _DropdownWithLabel extends StatefulWidget {
  final String label;
  final List<String> dropdownItems;
  _DropdownWithLabel(this.label, this.dropdownItems);
  @override
  State<StatefulWidget> createState() =>
      _DropdownWithLabelState(label, dropdownItems);
}

class _DropdownWithLabelState extends State {
  final String label;
  final List<String> dropdownItems;
  String selectedItem;
  _DropdownWithLabelState(this.label, this.dropdownItems) {
    selectedItem = dropdownItems.first;
  }
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Text(label),
        Container(
          width: 150,
          child: DropdownButton<String>(
              value: selectedItem,
              onChanged: (newValue) {
                setState(() => selectedItem = newValue);
              },
              items: dropdownItems.map((value) {
                return DropdownMenuItem(
                  value: value,
                  child: Text(value),
                );
              }).toList()),
        )
      ],
    );
  }
}

【问题讨论】:

  • 你能显示 _dropDownWithLabel 小部件吗?
  • 是的 - 我编辑了帖子以包含这个

标签: firebase flutter google-cloud-firestore


【解决方案1】:

代码看起来和我的一样,可以正常工作。这取决于您的规则是什么样的。

错误可能是请求中包含的凭据无权访问其中一个文档。设置正确的权限应该可以解决问题。

【讨论】:

  • 规则设置为允许对任何人进行读取访问,而对仅经过身份验证的用户进行写入访问。我认为这应该可行。
【解决方案2】:

我通过杀死我的模拟器并重新启动解决了我的问题。显然有些东西阻止它正确连接到 Firestore。

【讨论】:

    猜你喜欢
    • 2019-09-29
    • 2020-08-28
    • 2021-01-27
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    相关资源
    最近更新 更多