Home > Software design >  Getting "Unhandled Exception: Null check operator used on a null value" while getting data
Getting "Unhandled Exception: Null check operator used on a null value" while getting data

Time:11-30

Hello Guys I am working on flutter project where I am getting user information from the firestore database but when I am getting that info it throws an exception

The Error:

E/flutter (18952): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
E/flutter (18952): #0      _ProfileState.getData (package:recipedia/Tabs/profile.dart:30:86)
E/flutter (18952): <asynchronous suspension>

My Code:

Future<void> getData() async {
  emailFromPrefs = (await SharedPreference().getCred('email'))!;
  nameFromDatabase = (await UserModel().getUser(emailFromPrefs, 'name'))!;

  setState(() {
    name = nameFromDatabase;
    email = emailFromPrefs;
  });
}

My Usermodel Class Get Data function:

Future<String?> getUser(String email, String data) async {
  try {
    CollectionReference users =
        FirebaseFirestore.instance.collection('users');
    final snapshot = await users.doc(email!).get();
    final data = snapshot.data() as Map<String, dynamic>;
    return data['$data'];
  } catch (e) {
    return 'Error fetching user';
  }
}

CodePudding user response:

instead of using ! try to do a null check 1st.

Future<void> getData() async {
  final mEmail = await SharedPreference().getCred('email');
  if(mEmail==null){
     debugPrint("Got null on email");
     return;}
 
   emailFromPrefs = mEmail;
   final mName = await UserModel().getUser(emailFromPrefs, 'name');
 
   if(mName ==null){
     debugPrint("Got null on name");
     return;
   }
   nameFromDatabase  = mName;

  setState(() {
    name = nameFromDatabase;
    email = emailFromPrefs;
  });
}

Same goes for getUser, on users.doc(email!).get(). try-catch should handle this.

  • Related