Home > Software design >  The function can't be unconditionally invoked because it can be 'null' in flutter
The function can't be unconditionally invoked because it can be 'null' in flutter

Time:11-16

The function can't be unconditionally invoked because it can be 'null'.

getting an error in this part auth.currentUser:

FirebaseAuth auth = FirebaseAuth.instance;
final User user = await auth.currentUser();
String uid = user.uid;

await FirebaseFirestore.instance
        .collection('data')
        .doc(uid)
        .collection('data')
        .doc();

CodePudding user response:

try;

 FirebaseAuth auth = FirebaseAuth.instance;
final User user = await auth.currentUser;
String uid = user!.uid;
await FirebaseFirestore.instance.collection('data').doc(uid).collection('data').doc();

CodePudding user response:

User instance could be null and explicit conversion with the null assertion operator (user!.uid) is not a good practice, because it may cause a runtime exception.

therefore try this one:

FirebaseAuth auth = FirebaseAuth.instance;

final User? user = await auth.currentUser();
final String? uid = user?.uid;

if(user != null && uid != null) {
  // We have already tested 'uid' nullability, so now it is safe to use 'uid!'.
  await FirebaseFirestore.instance
          .collection('data')
          .doc(uid!)
          .collection('data')
          .doc();
} else {
  throw Exception('current user is null.');
}
  • Related