[英]Null check operator used on a null value on Flutter 2.5.3
我在 flutter 版本 2.5.3 上收到上述错误,并且在我尝试注销时发生。 显然,该错误与产品提供者有关,就像显示的错误一样。 但我仍然无法修复它。 它也可能与 null 安全有关,而且由于我不太熟悉它,我可能会遗漏一些东西。
> The following _CastError was thrown building _InheritedProviderScope<Products?>(dirty, dependencies: [_InheritedProviderScope<Auth?>], value: Instance of 'Products',
> listening to value):
> Null check operator used on a null value
The relevant error-causing widget was ChangeNotifierProxyProvider<Auth, Products>
main.dart
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => Auth()),
ChangeNotifierProxyProvider<Auth, Products>(
update: (context, auth, previousProducts) => Products(auth.token!, auth.userId,
previousProducts == null ? [] : previousProducts.items),
create: (_) => Products('', '', []),
),
ChangeNotifierProvider(create: (context) => Cart()),
ChangeNotifierProxyProvider<Auth, Orders>(
update: (context, auth, previousOrders) => Orders(auth.token!,
previousOrders == null ? [] : previousOrders.orders, auth.userId),
create: (_) => Orders('', [], ''),
),
],
child: Consumer<Auth>(
builder: (context, authData, child) => MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
fontFamily: 'Lato',
colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.purple)
.copyWith(secondary: Colors.deepOrange),
),
home: authData.isAuth ? ProductsOverviewScreen() : AuthScreen(),
//routes
),
));
auth.dart
class Auth with ChangeNotifier {
String? _token;
DateTime? _expiryDate;
String? _userId;
bool get isAuth {
return token != null;
}
String get userId {
return _userId!;
}
String? get token {
if (_expiryDate != null &&
_expiryDate!.isAfter(DateTime.now()) &&
_token != null) {
return _token;
}
return null;
}
Future<void> _authenticate(
String email, String password, String urlSegment) async {
final url = Uri.parse(
"https://identitytoolkit.googleapis.com/v1/accounts:$urlSegment?key=AIzaSyAA9PShE7c2ogk5L13kI0mgw24HKqL72Vc");
try {
final response = await http.post(url,
body: json.encode({
'email': email,
'password': password,
'returnSecureToken': true
}));
final responseData = json.decode(response.body);
if (responseData['error'] != null) {
throw HttpException(responseData['error']['message']);
}
_token = responseData['idToken'];
_userId = responseData['localId'];
_expiryDate = DateTime.now()
.add(Duration(seconds: int.parse(responseData['expiresIn'])));
} catch (error) {
throw error;
}
notifyListeners();
}
Future<void> logout() async {
_token = null;
_userId = null;
_expiryDate = null;
notifyListeners();
}
}
This issue was actually caused by the null check operator ( !
) added to the non-nullable String
variable auth.token
in your main.dart
file, which basically promises Dart that the value of auth.token
would never be null, and that promise未保留,因为您的auth.dart
文件中的logout()
方法中的_token
变量设置为 null 并且您的_token
实际上已传递给您使用 auth.token 调用的token
auth.token!
在您的main.dart
文件中。
您当然可以通过从main.dart
文件中的auth.token
变量中删除 null 检查运算符并将其设置为空String
来轻松解决此问题,如果它的值等于 Z37A6259CC0C1DAE299A786648,则
ChangeNotifierProxyProvider<Auth, Products>(
create: (_) => Products('', '', []),
update: (ctx, auth, previousProducts) => Products(
auth.token ?? '',
auth.userId ?? '',
previousProducts == null ? [] : previousProducts.items,
),
),
您还应该像这样使您的 userId getter 可以为空,否则会引发另一个错误:
String? get userId {
return _userId;
}
??
Dart 中的运算符基本上是一个赋值运算符,当它用于的变量等于 null 时执行。
这是 Dart 团队关于使用 null 安全性的额外指南: https://dart.dev/null-safety
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.