无法将参数类型 'String?' 分配给参数类型 'String' in flutter for shared prefrances

The argument type 'String?' can't be assigned to the parameter type 'String' in flutter for shared prefrances

所以我在 flutter 应用程序中使用共享首选项,但出现此错误: 参数类型'String?'无法赋值给参数类型'String' 这是代码:

if (result != null) {
      SharedPreferenceHelper().saveUserEmail(userDetails.email);
    }

错误是userDetils.email有人可以帮忙吗 A picture of what it shows

这是两种不同的类型。你需要强制String?通过 null 强制运算符转换为 String:userDetails.email! 或者如果它为 null 则为其提供默认值:userDetails.email ?? ''

是健全的空安全问题 String? 表示赋值给 Stirng 的变量是什么? type 可以为 null 或 null 值可用 ,因此请确保通过提供 userDetils.email?? 来检查它是否为空,这意味着 userDetils.email 是否为空

查看图片后,第 30 行声明指出:

User? userDetails = result.user;// Which potentially means that variable userDetails could be null

虽然 class 用户详细信息未共享,但已深入探讨该问题,我很确定 class User 有一个电子邮件参数,其声明包含其数据类型String? email 类似这样的前缀为 finallate.

在这种情况下,发生的情况是您具有嵌套的无效级别,用于从 userDetails 对象访问 email 变量。 这意味着:

Case 1=> userDetails is null and email is null.
Case 2=> userDetails is not null and email is null.
Case 3=> userDetails is not null and email is not null.

Meaning both `userDetails` and `email` have a datatype of which defines them to be null at compile time.

由于 dart 是静态类型语言,因此您需要在每个数据类型在编译时可为 null 的变量后添加 ! 以允许 dart 知道该变量中有数据并在稍后的某个时间被赋值在 运行 时间内。

因此,要解决此问题,您需要做的是将下面的行替换为第 33 行:

SharedPreferenceHelper().saveUserEmail(userdetails!.email ?? "Some default email");
// if you never want to save null as email pref else use the one below
SharedPreferenceHelper().saveUserEmail(userdetails!.email.toString());