Tobias Svendsen
Tobias Svendsen

Reputation: 125

Streambuilder snapshot is null and has error

I reinstalled flutter on my desktop, updated all packages and flutter version (currently running 2.2.3). For some reason, my StreamBuilder no longer works. I get the following error: "NoSuchMethodError: The getter 'isEmpty' was called on null."

This is the code of my widget:

Container(
                        color: Theme.of(context).scaffoldBackgroundColor,
                        child: Column(
                          children: <Widget>[
                            StreamBuilder<List<User>>(
                                initialData: [],
                                stream:
                                    DatabaseService().getChattingWith(user.uid),
                                builder: (context, snapshot) {
                                  switch (snapshot.connectionState) {
                                    case ConnectionState.waiting:
                                      return Loading();
                                    default:
                                      List<User> userList = snapshot.data;
                                      if (snapshot.hasError) {
                                        print("something went wrong");
                                      }
if (!snapshot.hasData)return Text("No data");
                                      print(userList);

                                      return userList.isEmpty
                                          ? Center(
                                              child: Container(
                                                padding: EdgeInsets.fromLTRB(
                                                    5, 100, 5, 10),
                                                child: Column(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.start,
                                                  children: [
                                                    Text("No Chats",
                                                        style: Theme.of(context)
                                                            .textTheme
                                                            .headline4),
                                                    SizedBox(
                                                      height: 30,
                                                    ),
                                                    Container(
                                                        width: 180.0,
                                                        height: 180.0,
                                                        decoration:
                                                            new BoxDecoration(
                                                          shape:
                                                              BoxShape.circle,
                                                          border: Border.all(
                                                            color: Theme.of(
                                                                    context)
                                                                .accentColor,
                                                            width: 4,
                                                          ),
                                                          image:
                                                              new DecorationImage(
                                                            image: new ExactAssetImage(
                                                                'assets/splashscreen.png'),
                                                            fit: BoxFit.cover,
                                                          ),
                                                        )),
                                                    SizedBox(
                                                      height: 40,
                                                    ),
                                                    Align(
                                                      alignment:
                                                          Alignment.center,
                                                      child: ArrowElement(
                                                        id: 'arrow',
                                                        show: true,
                                                        targetId: "profile",
                                                        tipLength: 20,
                                                        width: 5,
                                                        bow: 0.31,
                                                        padStart: 30,
                                                        padEnd: 43,
                                                        arcDirection:
                                                            ArcDirection.Right,
                                                        sourceAnchor:
                                                            Alignment.center,
                                                        targetAnchor:
                                                            Alignment(0, 0),
                                                        color: Theme.of(context)
                                                            .accentColor,
                                                        child: Column(
                                                          children: [
                                                            Text(
                                                                "Search to find matches",
                                                                style: Theme.of(
                                                                        context)
                                                                    .textTheme
                                                                    .headline5),
                                                          ],
                                                        ),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            )
                                          : ListView.builder(
                                              physics: BouncingScrollPhysics(),
                                              itemCount: userList.length,
                                              itemBuilder: (context, index) {
                                                return UserTile(
                                                  currentUser: user,
                                                  user: userList[index],
                                                );
                                              },
                                            );
                                  }
                                }),
                          ],
                        ),
                      ),

When running the code the "something went wrong" is executed and printing the userList results in null. The code for the Stream is:

//Userlist from snapshot
  List<User> _userListFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.docs.map((doc) {
      return User(
          uid: doc['uid'],
          radius: doc['radius'] ?? 1,
          searching: doc['searching'] ?? false,
          searchTime: doc['searchTime'],
          timestamp: doc['timestamp'],
          displayName: doc['displayName'],
          email: doc['email']);
    }).toList();
  }
  //Get chattingWith stream
  Stream<List<User>> getChattingWith(String uid) {
    return FirebaseFirestore.instance
        .collection('users/$uid/chattingWith')
        .snapshots()
        .map(_userListFromSnapshot);
  }

The chattingWith collection only contains the documentID, isSeen which is a bool and matchTime which is a TimeStamp. But it has previously not been a problem to map the snapshot with _userListFromSnapshot.

I simply don't understand why this is happening. Any input is greatly appreciated.

Upvotes: 0

Views: 1330

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

There are many more states the stream can be in, but you're only handling ConnectionState.waiting and "everything else".

If you keep your code as is, you should check whether the snapshot has data before accessing its data assuming that it exists:

if (!snapshot.hasData) return Text("No data");
return userList.isEmpty
  ...

Upvotes: 1

Related Questions