Flutter streamSnapshot.data.docs not working



试图抓取我的流快照长度,但由于某种原因。docs不工作。它说docs不能在一个对象上调用,但是我不明白为什么它会读取我的streamSnapshot作为一个对象,当它应该是一个流。

return Scaffold(
body: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('chats/khgvkhvfkftkh/messages')
.snapshots(),
builder: (ctx, streamSnapshot) {
if (streamSnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
final documents =
streamSnapshot.data.docs.length;
return ListView.builder(
itemCount: documents.length, //does not work due to error in declaration of documents
itemBuilder: (ctx, index) => Container(

您正在将documents设置为长度docs属性

final documents = streamSnapshot.data.docs.length;

所以当你之后做documents.length时,那是streamSnapshot.data.docs.length.length,它确实不存在。

给定变量名,我希望您将documents设置为:

final documents = streamSnapshot.data.docs;
return Scaffold(
//Just change the type of streamBuilder from object to dynamic, it will solve the error.
body: StreamBuilder<dynamic>(
stream: FirebaseFirestore.instance
.collection('chats/k4dtLMCeacmpFMBf8sA9/messages')
.snapshots(),
builder: (ctx, streamSnapshot) {
if (streamSnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: streamSnapshot.data!.docs.length,
itemBuilder: (ctx, index) => Container(
padding: const EdgeInsets.all(8),
child: const Text('This Works'),
),
);
}),

如果您是第一次遇到这个挑战,解决方案是定义StreamBuilder构建器属性,如下所示

return Scaffold(
body: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Add your collection specific url')
.snapshots(),
builder:(ctx, AsyncSnapshot<dynamic>streamSnapshot){ //Change here
if(streamSnapshot.connectionState == ConnectionState.waiting){
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount:streamSnapshot.data.docs.length,
itemBuilder: (ctx, index)=>Container(
padding: EdgeInsets.all(20),
child: const Text('This works')
),
);
},
),

相关内容

  • 没有找到相关文章

最新更新