Michael Gao
Michael Gao

Reputation: 63

NoSuchMethodError: invalid member on null (Flutter Web)

I am making a Card list that gets data from a Firestore database for a Flutter Web application, but this error is thrown:

 - "The following JSNoSuchMethodError was thrown building
   UserList(dirty, dependencies: [InheritedProvider<List<ClientUser>>],
   state: _UserListState#ab779): NoSuchMethodError: invalid member on
   null: 'length'"

Here is the code that I am using to build the list:

class _UserListState extends State<UserList> {
  @override
  Widget build(BuildContext context) {
    final users = Provider.of<List<ClientUser>>(context);

    return ListView.builder(
      itemBuilder: (context, index) {
        return UserTile(user: users[index]);
      },
      itemCount: users.length,
    );
  }

In my database service file, here is how I get the snapshot from the database and get the list from the snapshot:

List<ClientUser> _clientListFromSnapshot(QuerySnapshot snapshot) {
  return snapshot.documents.map((doc) {
    return ClientUser(
        name: doc.data['name'] ?? '', difficulty: doc.data['difficulty'] ?? 5);
  }).toList();
}

// get users stream
Stream<List<ClientUser>> get users {
  return userCollection.snapshots().map(_clientListFromSnapshot);
}

Here is how I declare the StreamProvider:

return StreamProvider<List<ClientUser>>.value(
      value: UserDatabaseService().users,

Where am I going wrong??

Upvotes: 4

Views: 11815

Answers (1)

Omatt
Omatt

Reputation: 10453

As previously mentioned in the comments, it's likely that checking the values of an empty List causes the error. A simple null checker should fix the issue.

final users = Provider.of<List<ClientUser>>(context);
if (users != null && users.length > 0){
  return ListView.builder(
    itemBuilder: (context, index) {
      return UserTile(user: users[index]);
    },
    itemCount: users.length,
  );
}
else {
  // Display loading widget
  
}

Upvotes: 3

Related Questions