2

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 ?

balu k
  • 3,515
  • 2
  • 14
  • 29
  • 1
    Check [this answer](https://stackoverflow.com/questions/67437038/how-to-access-shared-preferences-string-in-build-method-flutter/67437266#67437266) – croxx5f Jun 13 '21 at 22:07
  • Means MyApp constructor will be called multiple times you say ? – balu k Jun 13 '21 at 22:12
  • 2
    Yes it will, flutter widgets build methods and constructors should be idempotent/side-effect-free. And when you do need side effects like async operations do that in the state that is preserved between rebuilds. – croxx5f Jun 13 '21 at 22:14
  • 1
    I had another Statefulwidget which is same as this but that works without errors. This other widget is called when a button is clicked (NewScreen) – balu k Jun 13 '21 at 22:33

0 Answers0