Reputation: 21
I have a collection called Todos in Firestore with 3 possible properties (id, text and checked). So far i have succeeded on creating and saving todo's. Now i want them in a Listview but it returns an error on hot restart:
════════ Exception caught by widgets library ═══════════════════════════════════
type 'Null' is not a subtype of type 'String'
The relevant error-causing widget was
StreamBuilder<QuerySnapshot<Object?>>
My code for displaying the ListView:
final Stream<QuerySnapshot> _todostream =
FirebaseFirestore.instance.collection('Todos').snapshots();
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Styles.bgColor,
floatingActionButton: FloatingActionButton(
onPressed: createNewTask,
child: const Icon(Icons.add),
),
body: StreamBuilder(
stream: _todostream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
return ListView(
children: snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return ListTile(title: Text(data['text']));
}).toList(),
);
},
),
);
}
}
I hoped to see a listview with the results of my collection, it contains 2 items.
Upvotes: 0
Views: 159
Reputation: 63569
It would be better to accept null and check if it contains data or not.
body: StreamBuilder(
stream: _todostream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
if (snapshot.hasData) {
final data = snapshot.data?.docs.map((e) => e.data()).toList();
if (data == null) {
return Text("got null data");
}
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
final map = data[index] as Map?;
return ListTile(title: Text("${map?['text']}"));
});
}
return Text("NA");
},
),
Upvotes: 1