Search code examples
androidflutterdartsharedpreferences

The following _CastError was thrown building Game-Null check operator used on a null value--Flutter


I have a Problem with Shared Preference. How can I make a IF else operation with Shared Preference Bool Value? The Console show me: The following _CastError was thrown building Game(dirty, dependencies: [_LocalizationsScope-[GlobalKey#0453f], _InheritedTheme], state: _GameState#6a56a): Null check operator used on a null value

My Code:

    @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();
                                    },

Solution

  • It doesn't look like the line that causes that error is in the code snippet, but perhaps this will help:

    In Dart (with null safety enabled), there are nullable and non-nullable variables:

    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
    

    You can't do much with a nullable variable, because if it is null, calling a method on it is an error (the classic null dereference error).

    Dart is usually pretty smart about automatically converting between nullable and non-nullable types where it is safe:

    String? maybeNull = ...  // some maybe null string
    if (maybeNull != null) {
      // compiler can prove that maybeNull is non-null here
      print(maybeNull.length());  // this is allowed
    }
    

    However, sometimes as the programmer, you know that a variable is non-null, but the compiler cannot prove it. In these cases, you use ! to forcibly convert:

    String? maybeNull = 'hello';
    String notNull = maybeNull!;  // OK
    
    String? maybeNull = null;
    String uhOh = maybeNull!;  // runtime error: null-check operator used on null value
    

    To fix your issue, go to the section of code that the error points to, and check for uses of this null check operator !. It looks like it happened in a widget build method, so check that the value it's used on really can never be null, or handle the case where it is null (perhaps the data hasn't loaded yet?).