SharedPreferences: Unhandled Exception: Null check operator used on a null value

Viewed 425

This is the whole code file when running getInstance() on SharedPreferences it throws "Null check operator used on a null value" error. but works when getInstance is called in initState

import 'package:flutter/material.dart';

import 'package:shared_preferences/shared_preferences.dart';

main(List<String> args) {
  runApp(MaterialApp(home: MyApp()));
}

// ignore: must_be_immutable
class MyApp extends StatefulWidget {
  SharedPreferences sharedPreferences;
  MyApp() {
    SharedPreferences.getInstance().then((value) {
      sharedPreferences = value;
    });
  }
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Column(
        children: [
          Text(
            "${(widget.sharedPreferences != null) ? 
widget.sharedPreferences.getInt('count') ?? 'no count found' : ''}",
              ),
              ElevatedButton(
                onPressed: () => setState(() {}),
                child: Text("setState"),
              ),
            ],
          ),
        ));
      }
}

Why does this happen ?

0 Answers
Related