简体   繁体   中英

How to fix flutter firestore stream builder error?

I tired to get data from firestore in flutter app.

This is my code

body: StreamBuilder(
          stream:
              FirebaseFirestore.instance.collection('my_contact').snapshots(),
          builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
            return ListView.builder(
              itemCount: streamSnapshot.data.docs.length,
              itemBuilder: (ctx, index) => SettingRowWidget(
                "Call",
                vPadding: 0,
                showDivider: false,
                onPressed: () {
                  Utility.launchURL((streamSnapshot.data.docs[index]['phone']));
                },
              ),
            );
          },
        )); 

and this code getting right data but problem is i'm getting error like this.

════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building StreamBuilder<QuerySnapshot>(dirty, state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#7adda):
The getter 'docs' was called on null.
Receiver: null
Tried calling: docs

I dont know how to solve it. Can anyone guide me to solve this?

Check if it's null while loading the data from firestore

StreamBuilder(
        stream:
        FirebaseFirestore.instance.collection('my_contact').snapshots(),
        builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
          if (!streamSnapshot.hasData) return Center();
          if (streamSnapshot.data.docs.length!=0) {
            return ListView.builder(
              itemCount: streamSnapshot.data.docs.length,
              itemBuilder: (ctx, index) => SettingRowWidget(
                "Call",
                vPadding: 0,
                showDivider: false,
                onPressed: () {
                  Utility.launchURL((streamSnapshot.data.docs[index]['phone']));
                },
              ),
            );
          }else{
            return Center(child:Text('No data found'));
          }
    
        },
      ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM