Home > Back-end >  StreamBuilder snapshot always returns empty value and null safety error
StreamBuilder snapshot always returns empty value and null safety error

Time:01-29

This is the code that I have implemented to get the data that can be seen on the home page of WhatsApp, i.e. the profile photo, name of the contact, last message, and the time sent of a Individual/Group Chat ListTile.

    return firestore
        .collection('users')
        .doc(auth.currentUser!.uid)
        .collection('chats')
        .snapshots()
        .asyncMap((event) async {
      List<ChatContact> contacts = [];
      for (var document in event.docs) {
        var chatContact = ChatContact.fromMap(document.data());

        var userData = await firestore
            .collection('users')
            .doc(chatContact.contactID)
            .get();

        var user = model.User.fromMap(userData.data()!);

        contacts.add(
          ChatContact(
            name: user.name,
            profilePic: user.photoURL,
            contactID: chatContact.contactID,
            timeSent: chatContact.timeSent,
            lastMessage: chatContact.lastMessage,
          ),
        );
      }

      return contacts;
    });

I am calling this in a StreamBuilder to get the list of the contacts in the following way:

 StreamBuilder<List<ContactList>>(
              stream: ref.watch(chatControllerProvider).getchatContacts(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const CircularProgressIndicator();
                }
                return ListView.builder(
                    shrinkWrap: true,
                    itemCount: snapshot.data!.length,
                    itemBuilder: (context, index) {
                      var chatContactData = snapshot.data![index];
                      return Column(
                        children: [
                          InkWell(
                              onTap: () {
                                Navigator.pushNamed(
                                    context, UserChatScreen.routeName,
                                    arguments: {
                                      'name': 'rr',
                                      'selectedContactUID': 'uid'
                                    });
                              },
                              child: const ListTile(
                                title: Text(
                                  'name',
                                  style: const TextStyle(
                                    fontSize: 18,
                                  ),
                                ),
                                subtitle: Padding(
                                  padding: const EdgeInsets.only(top: 6.0),
                                  child: Text(
                                    ' lastMessage',
                                    style: const TextStyle(fontSize: 15),
                                  ),
                                ),
                                leading: CircleAvatar(
                                  backgroundImage: NetworkImage(
                                    'https://png.pngitem.com/pimgs/s/649-6490124_katie-notopoulos-katienotopoulos-i-write-about-tech-round.png',
                                  ),
                                  radius: 30,
                                ),
                                trailing: Text(
                                  'Date',
                                  style: const TextStyle(
                                    color: Colors.grey,
                                    fontSize: 13,
                                  ),
                                ),
                              ))
                        ],
                      );
                    });
              }),

This is the error that I'm also facing right now:

Null check operator used on a null value The relevant error-causing widget was StreamBuilder<List>'

CodePudding user response:

You are trying to return ListView with data, when snapshot still doesn't have data.

wrap the entire ListView.builder inside if(snapshot.hasData)

if(snapshot.hasData){
 return ListView.builder(
                    shrinkWrap: true,
                    itemCount: snapshot.data!.length,
                    itemBuilder: (context, index) {
                      var chatContactData = snapshot.data![index];
                      return Column(
                        children: [
                          InkWell(
                              onTap: () {
                                Navigator.pushNamed(
                                    context, UserChatScreen.routeName,
                                    arguments: {
                                      'name': 'rr',
                                      'selectedContactUID': 'uid'
                                    });
                              },
                              child: const ListTile(
                                title: Text(
                                  'name',
                                  style: const TextStyle(
                                    fontSize: 18,
                                  ),
                                ),
                                subtitle: Padding(
                                  padding: const EdgeInsets.only(top: 6.0),
                                  child: Text(
                                    ' lastMessage',
                                    style: const TextStyle(fontSize: 15),
                                  ),
                                ),
                                leading: CircleAvatar(
                                  backgroundImage: NetworkImage(
                                    'https://png.pngitem.com/pimgs/s/649-6490124_katie-notopoulos-katienotopoulos-i-write-about-tech-round.png',
                                  ),
                                  radius: 30,
                                ),
                                trailing: Text(
                                  'Date',
                                  style: const TextStyle(
                                    color: Colors.grey,
                                    fontSize: 13,
                                  ),
                                ),
                              ))
                        ],
                      );
                    });
}
return CircularProgressIndicator(); //            
  • Related