-1

I'm using flutter and firebase to make a to-do list. It keeps showing me this error even after I checked if my snap.data == null .But I am not sure why still doesn't work.

please help. I have checked similar problems like this but still didn't solve sorry for my English

 body: StreamBuilder(
 
      stream: Firestore.instance.collection("MyTodos").snapshots(),
      builder: (context, snapshots) {
        return ListView.builder(
   
          shrinkWrap: true,
          itemCount: snapshots.data.documents.length,
          itemBuilder: (context, index) {
            DocumentSnapshot documentSnapshot =
                snapshots.data.documents[index];
            return Dismissible(
              key: Key(index.toString()),
              child: Card(
                child: ListTile(
                  title: Text(documentSnapshot["todoTitle"]),
                  trailing: IconButton(
                    icon: Icon(Icons.delete),
                    onPressed: () {
                      setState(() {
                        todos.removeAt(index);
                      });
                    },
                  ),
                ),
              ),
            );
          },
        );
      },
    )

1 Answers1

1

StreamBuilder has a default state before it gets any data at all, and you need to check for this state so you don't try to build using data that doesn't exist yet. You can do this by checking either snapshots.hasData or snapshots.data == null:

StreamBuilder(
  ...
  builder: (context, snapshots) {
    if (!snapshots.hasData) {
      return CircularProgressIndicator();
    }
    else {
      return ListView.builder(
        ...
      );
    }
  },
),
Abion47
  • 22,211
  • 4
  • 65
  • 88
  • thank you very much the error removed. It seems I forget to put else in the code . I can't put this as the answer because my reputation still low than 15. –  Feb 21 '21 at 18:59
  • @nadacoco If this answer helped, please consider marking it as correct so that future users with the same question can more easily find it. :) – Abion47 Feb 21 '21 at 19:00
  • I marked it . But still, when I enter my data it doesn't show my todo. –  Feb 21 '21 at 19:26
  • @nadacoco Then that is probably a separate issue. I'd recommend trying to pinpoint the cause and, if needed, start a new question about that. – Abion47 Feb 22 '21 at 18:37
  • thanks for caring I fixed it by flutter run in the terminal. –  Mar 02 '21 at 18:18