Dart itemcount中的snapshot.data.length不起作用:";吸气剂';长度';被调用时为null“;

Dart itemcount中的snapshot.data.length不起作用:";吸气剂';长度';被调用时为null“;,dart,flutter,google-cloud-firestore,Dart,Flutter,Google Cloud Firestore,我正在尝试使用以下代码从firestore获取文档: Future getCategories() async { var firestore = Firestore.instance; QuerySnapshot qn = await firestore.collection("categories").getDocuments(); return qn.documents; } @override Widget build(BuildContext co

我正在尝试使用以下代码从firestore获取文档:

 Future getCategories() async {
    var firestore = Firestore.instance;
    QuerySnapshot qn = await firestore.collection("categories").getDocuments();
    return qn.documents;
  }

 @override
  Widget build(BuildContext context) {
    return Container(
      child:FutureBuilder(
        future:getCategories(),
        builder:(context, snapshot){
          if(snapshot.connectionState == ConnectionState.waiting){
            return Center(
              child:Text("Loading...")
            );
         }
         else
         {
           return GridView.builder(
             itemCount: snapshot.data.length,
             gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
                 crossAxisSpacing: 6.0, mainAxisSpacing: 6.0, crossAxisCount: 2),
              itemBuilder: (BuildContext context, int index) {
                return SingleCategory(
                  category_name:  snapshot.data[index].data["title"],
                  category_picture: snapshot.data[index].data["picture"],
                );
              }
           );
         }
        }
      )
    );
运行代码时,出现以下错误:

I/颤振(7555):══╡ WIDGETS库捕获到异常 ╞═══════════════════════════════════════════════════════════ I/颤振 (7555):以下NoSuchMethodError被抛出到建筑中 FutureBuilder(脏,状态:I/颤振(7555): _FutureBuilderState#c3e7b):I/flatter(7555):getter“length”在null上被调用。I/颤振(7555):接收器:空 I/颤振(7555):尝试呼叫:长度I/颤振(7555):I/颤振 (7555):当抛出异常时,这是堆栈:I/flatter (7555):#0 Object.noSuchMethod (dart:core/runtime/libobject_补丁。dart:50:5)


谁能帮帮我吗

正如我们在评论中发现的,您使用的是身份验证规则,该规则拒绝所有请求的访问:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
       allow read, write: if false;
    }
  }
}
我想你想写这样的东西(只读模式):


尝试此规则

您应该在FutureBuilder小部件中添加initialData属性,并将其设置为[]空列表。例如:

FutureBuilder(  // only add initialData: []
    initilData: [],  // this is vital to get rid of null length error
    future:getCategories(),
    builder:(context, snapshot){
      if(snapshot.connectionState == ConnectionState.waiting){
        return Center(
          child:Text("Loading...")
        );
     } // and same code goes below
所以,我们的主要目标是防止空长度错误,通过向空数组添加initialData属性可以解决我们的问题。 这是该地产的官方定义---

将用于创建提供的快照的数据,直到 非空未来已完成。 此外,我们还可以添加一些加载小部件,以避免向用户显示空屏幕


我们可以添加一个条件“当快照具有等于空数组(或data.length==0)的数据时,如果它是show loading widget else show list”。

最简单的方法是使用快照的hasData参数

if (snapshot.hasData) { return GridViewBuilder(...);} 
试试这个:

 future: getData(),
              builder: (context, AsyncSnapshot<List<User>> snapshot)
future:getData(),
生成器:(上下文,异步快照)

错误消息是明确的,您的
快照。数据
为空。如果使用
FutureBuilder
,请不要等待结果。我使用的是本教程:。为什么Wait不与FutureBuilder合作?顺便说一句,我删除了等待,我仍然得到相同的error@bangbang只需打开调试器并检查
快照
对象。请注意字段
snapshot.error
snapshot.connectionState
对不起,我的意思是您不一定需要
FutureBuilder
,因为您在
wait
语句之后就已经得到了结果<代码>变量结果=等待getCategories();打印(“完成”)应该与
getCategories()相同。然后((结果){print('done');})
这与
FutureBuilder(future:getCategories(),builder:(context,snapshot){print('done');})相同。但事实上,这可能不是问题的根源。以下是我发现的:连接状态是ConnectionState。等待快照错误是PlatformException(执行getDocuments时出错,权限被拒绝:缺少或权限不足,null)。太棒了!这就是我需要的!完美虽然这段代码可以解决这个问题,但如何以及为什么解决这个问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。
 future: getData(),
              builder: (context, AsyncSnapshot<List<User>> snapshot)