【问题标题】:I have a problem with Null Safety an the problem is 'Null check operator used on a null value' [duplicate]我对空值安全有疑问,问题是“空值检查运算符用于空值”[重复]
【发布时间】:2022-01-06 19:06:51
【问题描述】:

从 firebase 获取一些数据并使用模型对其进行解码时发生这种情况, 这是方法:

UserModel? userModel;
void getUser() {
emit(GetUserLoadingsState());

FirebaseFirestore.instance.collection('users').doc(uId).get().then((value) {
  userModel = UserModel.fromJson(value.data()!);
  emit(GetUserSuccessState());
}).catchError((error) {
  emit(GetUserErrorState(error.toString()));
});

}

调用方法

return BlocProvider(
  create: (BuildContext context) => AppCubit()..getUser(),
  child: BlocConsumer<AppCubit, AppStates>(
    listener: (context, state) {},
    builder: (context, state) {
      return MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: lightTheme,
        home: startWidget,
      );
    },
  ),
);

和消费者

BlocConsumer<AppCubit, AppStates>(
  listener: (context, state) {},
  builder: (context, state) {
    var user = AppCubit.get(context).userModel!;

【问题讨论】:

  • 我成功从firebase获取数据,但是在使用用户模型时发生了错误。

标签: flutter bloc dart-null-safety cubit null-safety


【解决方案1】:

为了您的错误消息和代码,您在 2 个字段中使用了空检查运算符 !

  1. 字段应该是这样的;
UserModel? userModel;
void getUser() {
emit(GetUserLoadingsState());

FirebaseFirestore.instance.collection('users').doc(uId).get().then((value) {
  if (value.exists) {
    userModel = UserModel.fromJson(value.data()!);
    emit(GetUserSuccessState());
  }
}).catchError((error) {
  emit(GetUserErrorState(error.toString()));
});
  1. 字段应该是这样的;
BlocConsumer<AppCubit, AppStates>(
  listener: (context, state) {},
  builder: (context, state) {
    if (AppCubit.get(context).userModel != null)
      var user = AppCubit.get(context).userModel!;

除非您知道自己的值不为空,否则不应使用 ! 空检查运算符。

【讨论】:

猜你喜欢
  • 2021-09-28
  • 2021-08-30
  • 2022-01-11
  • 2021-10-27
  • 2021-12-03
  • 2022-01-18
  • 2021-11-03
  • 2021-01-24
  • 2022-07-06
相关资源
最近更新 更多