Search code examples
firebasefluttergoogle-cloud-firestoreruntime-error

The getter 'docs' was called on null. Receiver: null Tried calling: docs


when I run my app, there is always an error appears which is:

The getter 'docs' was called on null.
Receiver: null
Tried calling: docs

but everything works correctly, How can I solve it? I think there is an update to flutter which make this code wrong, because I faced many problems like that. important parts in my code:

return StreamBuilder(
        stream: FirebaseFirestore.instance
        .collection('medicine')
        .where('userId', isEqualTo: user.uid)
        .snapshots(),
    builder: (context, snapshot) {

    final doc = snapshot.data.docs;
    return ListView.builder(
    itemCount: doc.length,
    itemBuilder: (ctx, index) {

    if (snapshot.data == null) {
    return Center(
    child: CircularProgressIndicator(),
    );
    }
    return Container(
    child: Stack(
    children: [
    Row(
    children: [
    Flexible(
    child: Column(
    children: [
    Text(
    'اسم الدواء: ' + doc[index]['medicationName'],
    textAlign: TextAlign.start,
    ),
    ],
    ),
    )
    ],
    ),
    ],
    ),
    );
    },
    ));

Solution

  • The first stream can emit an empty snapshot.

    You should check if the snapshot has data before accessing the documents:

    if(!snapshot.hasData) {
     return Center(child: CircularProgressIndicator());
    } 
    // if it has data, do your thing:
    final doc = snapshot.data.docs;
    return ListView( ..... )