无法无条件调用该函数,因为它在flutter中可能为“null”

zc0qhyus  于 2022-11-17  发布在  Flutter
关注(0)|答案(2)|浏览(161)

无法无条件调用该函数,因为它可以为“null”。
获取此部分中的错误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();
plicqrtu

plicqrtu1#

尝试;

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

eoxn13cs2#

User示例可以是null,使用空Assert运算符(user!.uid)进行显式转换不是一种好的做法,因为它可能会导致运行时异常。
所以试试这个:

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

相关问题