在构建用于空值的 Game-Null 检查运算符时抛出了以下 _CastError--Flutter

时间:2021-07-23 20:26:27

标签: android flutter dart sharedpreferences

我有共享偏好的问题。如何使用 Shared Preference Bool Value 进行 IF else 操作? 控制台显示我: 以下 _CastError 在构建 Game(dirty, dependencies: [_LocalizationsScope-[GlobalKey#0453f], _InheritedTheme], state: _GameState#6a56a) 时被抛出: 用于空值的空检查运算符

我的代码:

    @override
  void initState() {
    super.initState();
 ...

    _sprache();
    _gesamtPkt();
  }
...

  @override
  void dispose() {
    super.dispose();
  }

  ///Loading counter value on start (load)
  _sprache() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _deutsch = (prefs.getBool('deutsch') ?? true);
      print(Text("Deutsch: $_deutsch"));
    });
  }
...

PageRouteBuilder(
                                    pageBuilder:
                                        // ignore: missing_return
                                        (context, animation1, animation2) {
                                      if (_deutsch = true) return Game();
                                      return GameEN();
                                    },

1 个答案:

答案 0 :(得分:1)

看起来导致该错误的行不在代码片段中,但也许这会有所帮助:

在 Dart 中(启用了空安全),有可以为空和不可为空的变量:

RunModalLoop()

对于可空变量你不能做太多事情,因为如果它是空的,调用它的方法就是一个错误(经典的空引用错误)。

Dart 通常非常聪明,可以在安全的情况下自动在可空类型和不可空类型之间进行转换:

String nonNullable = 'hello';  // OK
String nonNullable = null;  // compile time error

String? nullable = 'hello';  // OK
String? nullable = null;  // OK

nullable.length() // compile time error, `nullable` might be null

然而,有时作为程序员,你知道一个变量是非空的,但编译器无法证明这一点。在这些情况下,您使用 String? maybeNull = ... // some maybe null string if (maybeNull != null) { // compiler can prove that maybeNull is non-null here print(maybeNull.length()); // this is allowed } 强制转换:

!

要解决您的问题,请转到错误指向的代码部分,并检查是否使用了此空检查运算符 String? maybeNull = 'hello'; String notNull = maybeNull!; // OK String? maybeNull = null; String uhOh = maybeNull!; // runtime error: null-check operator used on null value 。看起来它发生在一个小部件 ! 方法中,因此请检查它使用的值是否真的永远不会为空,或者处理它为空的情况(可能数据尚未加载?)。< /p>