简体   繁体   中英

Getting "Unhandled Exception: Null check operator used on a null value" while getting data from firestore database

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';
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM