微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法无条件访问属性“id”,因为接收者可以为“null”

如何解决无法无条件访问属性“id”,因为接收者可以为“null”

我正在尝试使用 (profileId: currentUser.id)

body: PageView(
    children: <Widget>[
      //Feed(),ElevatedButton(
        child: Text('Cerrar sesión'),onpressed: logout,),SubirPost(currentUser: currentUser),EditarPerfil(profileId: currentUser.id),],controller: pageController,onPageChanged: onPageChanged,physics: NeverScrollableScrollPhysics(),

但它给了我这个错误

The property 'id' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!').

我已经尝试过空检查(像这样:profileId: currentUser!.id)但是当我调试时它会抛出一个 Null check operator used on a null value 错误

id 在用户模型文件中是这样声明的:

class User {
  final String id;
  final String username;
  final String email;
  final String photoUrl;
  final String displayName;
  final String bio;

User(
  {required this.id,required this.username,required this.email,required this.photoUrl,required this.displayName,required this.bio});

factory User.fromDocument(DocumentSnapshot doc) {
return User(
  id: doc['id'],email: doc['email'],username: doc['username'],photoUrl: doc['photoUrl'],displayName: doc['displayName'],bio: doc['bio'],);}}

对于 profileId 是在另一个文件中:

 final String profileId;
 EditarPerfil({required this.profileId});

我已经尝试了我找到的所有东西

此外,当我尝试在用户模型 ? 上使用 final String id 时,我收到错误 The argument type 'String?' can't be assigned to the parameter type 'String'

final String profileId 相同

我正在导入 cloud_firestorefirebase_storagegoogle_sign_in 包。

解决方法

当您编写 currentUser!.id 时,您要确保 currentUser 不会为空。因此,当您的 currentUser 为 null 时,您将收到此错误:Null check operator used on a null value。因此,如果您有可能在调用 profileId 时获得 null 值,则必须使配置文件 ID 可为空。为此,只需通过 UserString? id 类中将 id 声明为可空。或者我推荐的另一种方法是使用 ?? 运算符 (reference),它只是一个表示 if null 的条件。您可以在 UserId 的赋值语句中使用它。 像这样:

body: PageView(
    children: <Widget>[
      //Feed(),ElevatedButton(
        child: Text('Cerrar sesión'),onPressed: logout,),SubirPost(currentUser: currentUser),EditarPerfil(profileId: currentUser.id ?? ''),// this is a check if the id is not null then it will return the actual value otherwise it will return the empty string.
    ],controller: pageController,onPageChanged: onPageChanged,physics: NeverScrollableScrollPhysics(),

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。