Home > Enterprise >  Exception caught by widgets library, Null check operator used on a null value
Exception caught by widgets library, Null check operator used on a null value

Time:07-07

I want to add a messaging plugin to my application, but I get the error "Null check operator used on a null value". I'm getting uid error, '?' next to String I put it but it doesn't work.

Error:

Type Null is not a subtype of type 'String'
Screenshot

This is my user model

    user.dart
    
    class User {
      late final String username;
      final String uid;
      final String email;
      late final String bio;
      final List followers;
      final List following;
      late final String photoUrl;
    
      User({
        required this.email,
        required this.uid,
        required this.photoUrl,
        required this.username,
        required this.bio,
        required this.followers,
        required this.following,
      });
    
      get state => null;
    
      Map<String, dynamic> toJson() => {
            'username': username,
            'uid': uid,
            'email': email,
            'photoUrl': photoUrl,
            'bio': bio,
            'followers': followers,
            'following': following,
          };
    
      static User fromSnap(DocumentSnapshot snap) {
        var snapshot = snap.data() as Map<String, dynamic>;
    
        return User(
          username: snapshot['username'],
          uid: snapshot['uid'],
          email: snapshot['email'],
          photoUrl: snapshot['photoUrl'],
          bio: snapshot['bio'],
          followers: snapshot['followers'],
          following: snapshot['following'],
        );
      }
    }

This is my user provider. user_provider

    class UserProvider with ChangeNotifier {
      User? myUser;
      final AuthMethods _authMethods = AuthMethods();
    
      User get getUser => myUser!;
    
      defineUser(String uid) async {
        CollectionReference refUsers =
            FirebaseFirestore.instance.collection('users');
        DocumentSnapshot doc = await refUsers.doc(uid).get();
        User thisUser = User.fromSnap(doc);
        myUser = thisUser;
        notifyListeners();
        return thisUser;
      }
    
      updateUserInfo(User updatedUser, String currentUserId) async {
        myUser?.bio = updatedUser.bio;
        myUser?.photoUrl = updatedUser.photoUrl;
        myUser?.username = updatedUser.username;
        notifyListeners();
        await DatabaseMethods().upDateUsersInfo(updatedUser, currentUserId);
      }
    
      Future<void> refreshUser() async {
        User user = await _authMethods.getUserDetails();
        myUser = user;
        notifyListeners();
      }
    }

this is my chat room chat_rooms

    class ChatRooms extends StatefulWidget {
      @override
      _ChatRoomsState createState() => _ChatRoomsState();
    }
    
    class _ChatRoomsState extends State<ChatRooms> {
      Stream<QuerySnapshot>? mySnapshot;
      int? chatCount = 0;
      TextEditingController searchController = TextEditingController();
      final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
    
      @override
      void dispose() {
        searchController.dispose();
        super.dispose();
      }
    
      getChatsCount() async {
        QuerySnapshot snapshot = await refUsers.get();
        void setStateIfMounted(f) {
          if (mounted) setState(f);
        }
    
        setStateIfMounted(() {
          chatCount = snapshot.docs.length - 1;
        });
      }
    
      @override
      void initState() {
        getChatsCount();
        super.initState();
      }
    
     
      @override
      Widget build(BuildContext context) {
        return SafeArea(
          child: Scaffold(
            key: _scaffoldKey,
            body: Column(
              children: [
                Container(
                  height: 13.5,
                  
                ),
                Container(
                  height: (1 / 6.7),
                  width: double.infinity,
                  color: Colors.grey[200],
                ),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 10.0),
                  child: TextField(
                    onChanged: (val) async {
                      Stream<QuerySnapshot> snapshot = refUsers
                          .where('username',
                              isGreaterThanOrEqualTo: searchController.text)
                          .snapshots();
                      setState(() {
                        mySnapshot = snapshot;
                      });
                    },
                    controller: searchController,
                    decoration: InputDecoration(
                        prefixIcon: Icon(
                          Icons.search,
                          color: kGreenColor,
                          size: 22.0,
                        ),
                        hintText: 'Search',
                        hintStyle:
                            myGoogleFont(Colors.black, 13.5, FontWeight.w500),
                        contentPadding: EdgeInsets.symmetric(horizontal: 10),
                        isDense: true,
                        enabledBorder: InputBorder.none,
                        focusedBorder: InputBorder.none),
                  ),
                ),
                Expanded(
                  child: StreamBuilder<QuerySnapshot>(
                    stream: mySnapshot == null ? refUsers.snapshots() : mySnapshot,
                    builder: (context, snapshot) {
                      if (!snapshot.hasData)
                        return Center(
                          child: CircularProgressIndicator(),
                        );
                      else {
                        chatCount = (snapshot.data!).docs.length;
                        return ListView.builder(
                            // reverse: true,
                            itemCount: (snapshot.data!).docs.length,
                            itemBuilder: (context, index) {
                              User friendUser =
                                  User.fromSnap((snapshot.data!).docs[index]);
                              String myUserId =
                                  Provider.of<UserProvider>(context, listen: false)
                                      .myUser!
                                      .uid;
    
                              if (friendUser.uid != myUserId) {
                                return UserTile(friendUser);
                              } else
                                return Container();
                            });
                      }
                    },
                  ),
                )
              ],
            ),
          ),
        );
      }
    }

CodePudding user response:

Most probably the snap in User.fromSnap is returning null on some of its values. To solve this you should do the following:

  • First, you should make sure the values are not null from the API/DB/whatever the snapshot comes from;
  • For the null ones, default them to another value like below with the ?? operator in a conditional expression;
      static User fromSnap(DocumentSnapshot snap) {
        var snapshot = snap.data() as Map<String, dynamic>;
    
        return User(
          username: snapshot['username'] ?? 'Unknown',
          uid: snapshot['uid'] ?? '0000000000',
          email: snapshot['email'] ?? '',
          photoUrl: snapshot['photoUrl'] ?? '',
          bio: snapshot['bio'] ?? '',
          followers: snapshot['followers'] ?? [],
          following: snapshot['following'] ?? [],
        );
      }
  • Related