This is my code
@override
Widget build(BuildContext context) {
return Scaffold(
body:StreamBuilder(
stream:FirebaseFirestore.instance
.collection('chats/r7T0B5xmCSgKQFLl2uNj/messages')
.snapshots(),
builder:(context,streamSnapshot) {
return ListView.builder(
itemCount: streamSnapshot.data!.docs.length,
itemBuilder:(ctx, index) =>
Container(
padding: const EdgeInsets.all(8),
child: const Text("This Work!"),
),);
} ,),
floatingActionButton: FloatingActionButton(
onPressed: (){},
),
);
}
}
When use null check operator on itemCount: streamSnapshot.data!.docs.length
, this line got an exception, with out null check there is an error
2
Answers
Check null for data length use null safety:
It will take some time to fetch data, so initially it will be null. The issue is caused by forcing not null with bang
!
.You can do
itemCount: streamSnapshot.data?.docs.length,
But better case,
Find more about using StreamBuilder