0

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.

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
Arjen A
  • 21
  • 3

1 Answers1

1

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");
  },
),
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • This has solved the issue. I first ran into another error but that was because the mapping was to 'text' instead of 'Text'. I dont know how to mark this as solved or how to thank you since this is my first post here. Thanks! – Arjen A Feb 05 '23 at 11:33
  • what do you get, empty text? Then it means we didn't provide the correct path or data is empty – Md. Yeasin Sheikh Feb 05 '23 at 11:36