0

I have the follwing problem with my code. When I call a Int with SharedPreference then show the emulator the error "_casterror (null check operator used on a null value)". The error is showing only when I start the app.When starting, the value should be _pktH = 0.

...    
int? _pktH;
...
     void initState() {
        super.initState();
        _loadCounterH();
}
 

_loadCounterH() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        setState(() {
          _counterH = (prefs.getInt('counterH') ?? 1);
          prefs.setInt('counterH', _counterH!);
          _pktH = (prefs.getInt('pktH') ?? 0);
          prefs.setInt('pktH', _pktH!);
          print(Text("Save number is: $_counterH"));
          print(Text("Save pkt is: $_pktH"));
        });
      }



 String _abzeichenH;

    if (_pktH! >= 2835) {
      _abzeichenH = ' ' + ' \u{1F451}' + ' ' + 'Ingenieur/-in';
    } else if (_pktH! >= 1890) {
      _abzeichenH = ' ' + '\u2692' + '\u2692' + '\u2692' + ' ' + 'Arbeiter/-in';
    } else if (_pktH! >= 1260) {
      _abzeichenH = ' ' + '\u2692' + '\u2692' + ' ' + 'Azubi';
    } else if (_pktH! >= 10) {
      _abzeichenH = ' ' + '\u2692' + ' ' + 'Praktikant/-in';
    } else {
      _abzeichenH = '';
    }
    print('Dein Abzeichen ist $_abzeichenH');

enter image description here

Bruno
  • 79
  • 1
  • 8
  • Is `_pktH` having value before read time? Can you find value for it on debugging? – Md. Yeasin Sheikh Aug 24 '21 at 14:26
  • Yes I load `_loadCounterH` with: `void initState() { super.initState(); _loadCounterH();´ as a result, ´_pktH´ should become ´0´ if it has the value ´null´. – Bruno Aug 24 '21 at 14:32
  • The thing I can assume(because cant see full snippet) here, ` _loadCounterH() async` is on loading mode and `_pktH` is using reading it value and getting null. – Md. Yeasin Sheikh Aug 24 '21 at 14:35
  • 1
    `_loadCounterH` is asynchronous. You are not guaranteeing that whatever code does `if (_pktH! >= 2835) {` runs after `_loadCounterH` completes. – jamesdlin Aug 24 '21 at 15:57
  • Thank you @jamesdlin but how do I solve my Problem? – Bruno Sep 11 '21 at 09:10
  • You haven't shown the code that calls Ensure that whatever code calls `_loadCounterH`. You should make the caller use `await` to wait for it to complete. If you have code that might run before it completes, then that code *cannot* use `_pktH!` and must check whether it's `null` first. – jamesdlin Sep 11 '21 at 09:26
  • Thanks. I have edit my question. I call `__loadCounterH` with `initState()`. How I use `await` in ` initState()`. Thanks a lot. – Bruno Sep 11 '21 at 10:17
  • 1
    You don't. Use a `FutureBuilder`. Also see https://stackoverflow.com/questions/63017280/ – jamesdlin Sep 12 '21 at 05:03

0 Answers0