【问题标题】:Null check operator used on a null value on Flutter 2.5.3在 Flutter 2.5.3 上用于空值的空值检查运算符
【发布时间】:2022-01-05 16:19:58
【问题描述】:

我在颤振版本 2.5.3 上遇到上述错误,当我尝试注销时发生此错误。显然,该错误与产品提供者有关,就像显示的错误一样。但我仍然无法修复它。它也可能与零安全性有关,而且由于我对它不是很熟悉,所以我可能会遗漏一些东西。

>         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>

ma​​in.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();
  }
}

【问题讨论】:

  • 我实际上不知道如何解决它,但我认为错误意味着auth.token 为空,当您这样做时Products(auth.token! 会引发错误因为它不希望该值为空

标签: android flutter dart mobile


【解决方案1】:

问题:

这个问题实际上是由添加到non-nullable String 变量auth.token 中的main.dart 文件中的空值检查运算符(!)引起的,这基本上向Dart 保证auth.token 的值永远不会为空,并且该承诺没有兑现,因为您的 auth.dart 文件中的 logout() 方法中的 _token 变量设置为 null 并且您的 _token 实际上被传递给您使用 auth.token! 调用的 token getter在您的main.dart 文件中。

解决方案:

您当然可以通过从main.dart 文件中的auth.token 变量中删除空检查运算符并将其设置为空String(如果它的值等于null)来轻松解决此问题,如下所示:

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

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 2021-02-25
    • 2023-01-05
    • 2022-06-15
    • 2021-08-30
    • 2021-12-03
    • 2021-11-06
    • 2021-06-17
    相关资源
    最近更新 更多