我对 Null Safety 有疑问,问题是 'Null check operator used on a null value'
I have a problem with Null Safety an the problem is 'Null check operator used on a null value'
从 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!;
为了您的错误消息和代码,您在 2 个字段中使用了空值检查运算符 !
;
- 字段应该是这样的;
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()));
});
- 字段应该是这样的;
BlocConsumer<AppCubit, AppStates>(
listener: (context, state) {},
builder: (context, state) {
if (AppCubit.get(context).userModel != null)
var user = AppCubit.get(context).userModel!;
除非您知道您的值不为空,否则不应使用 !
空值检查运算符。
从 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!;
为了您的错误消息和代码,您在 2 个字段中使用了空值检查运算符 !
;
- 字段应该是这样的;
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()));
});
- 字段应该是这样的;
BlocConsumer<AppCubit, AppStates>(
listener: (context, state) {},
builder: (context, state) {
if (AppCubit.get(context).userModel != null)
var user = AppCubit.get(context).userModel!;
除非您知道您的值不为空,否则不应使用 !
空值检查运算符。