简体   繁体   English

Null 检查运算符用于 Flutter 2.5.3 上的 null 值

[英]Null check operator used on a null value on Flutter 2.5.3

i´m getting the error above on flutter version 2.5.3, and it is happening when i try to logout .我在 flutter 版本 2.5.3 上收到上述错误,并且在我尝试注销时发生 Apparently the error has something to do with the Products provider, just like the error is showing.显然,该错误与产品提供者有关,就像显示的错误一样。 But i´m still not able to fix it.但我仍然无法修复它。 It may also have something to do with null safety, and since i´m not very acquainted to it, i might be missig something.它也可能与 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 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 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();
  }
}

Problem:问题:

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 was not kept because the _token variable in the logout() method in your auth.dart file was set to null and your _token is actually passed to your token getter that you call using auth.token! 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! in your main.dart file.在您的main.dart文件中。

Solution:解决方案:

You can of course easily fix this by removing the null check operator from the auth.token variable in your main.dart file and setting it to an empty String if it's value was equal to null, like this:您当然可以通过从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,
       ),
     ),

you should also make your userId getter nullable like this or it would throw another error:您还应该像这样使您的 userId getter 可以为空,否则会引发另一个错误:

String? get userId {
  return _userId;
}

the ?? ?? operator in Dart is basically an assignment operator that executes when the variable it is used for is equal to null. Dart 中的运算符基本上是一个赋值运算符,当它用于的变量等于 null 时执行。

And here's an extra guide from the Dart Team on working with null safety: https://dart.dev/null-safety这是 Dart 团队关于使用 null 安全性的额外指南: https://dart.dev/null-safety

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter 中的“用于 Null 值的 Null 检查运算符” - "Null check operator used on a Null Value" in Flutter Null 检查运算符用于 null 值 Flutter - Null check operator used on a null value Flutter Null 检查运算符用于 flutter 的 null 值 - Null check operator used on a null value for flutter 颤振:在空值上使用空检查运算符? - flutter: Null check operator used on a null value? Flutter “在 null 值上使用空检查运算符”错误 - Flutter "Null check operator used on a null value" error Flutter - _CastError(在 null 值上使用空检查运算符) - Flutter - _CastError (Null check operator used on a null value) Null 检查 WebView 中 null 值上使用的运算符 flutter - Null check operator used on a null value in WebView flutter Flutter / Firebase 项目 - 是“未处理的异常:Null 检查运算符在 Z37A625 上使用导致66489C1DAE2997 值? - Flutter / Firebase project - Is `Unhandled Exception: Null check operator used on a null value` causing a blank screen? 未处理的异常:未处理的错误 Null 检查运算符用于 flutter 中的“AuthBloc”实例中的 null 值 - Unhandled Exception: Unhandled error Null check operator used on a null value occurred in Instance of 'AuthBloc' in flutter 在 MaterialApp 中使用路由时,Flutter“在 null 值上使用的空检查运算符” - Flutter "null check operator used on a null value" while using routes in MaterialApp
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM