簡體   English   中英

Null 檢查運算符用於 Flutter 2.5.3 上的 null 值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM