Q:

SharedPreference value null on startup

There is a variable pinEnable which tells the app whether the user has set up a pin for the app. This is stored in SharedPreferences. My first page that comes in my app depends on it. Since the fetching operation is async, it just returns null.
the relevant code I used is given:- 
PinData is just a class containing functions to set and get pin and pinEnable
void main() => runApp(MyApp());

class MyApp extends StatefulWidget {

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool pinEnable;
  PinData pinData = PinData();

  updatePinEnable() async {
    pinEnable = await pinData.getPinEnable();
    print(pinEnable);
  }

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(...),
        home: pinEnable == false ? MyTabbedHome() : PinCodePage());
  }
}

In the last code statement pinEnable is not false but it's null, therefore it returns PinCodePage()
Is there any way to fix this, or any ideas to get around this. Thanks!!

A:

You don't need stateful widget
,and this is a better solution using a FutureBuilder to return the correct widget only when the async process is completed:
Edit: edited the code to address fact that you are not setting initial value in shared prefs
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  PinData pinData = PinData();

  Future<bool> isPinEnabled() async => pinData.getPinEnable();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
        future: isPinEnabled(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return CircularProgressIndicator();
          }
          else if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              return snapshot.data ?
              PinScreen() //if true returned from shared prefs go to pin screen
                  :
              HomeScreen(); //if false returned from shared prefs go to home screen
            }
            else {
              return HomeScreen(); //if null returned from shared prefs go to home screen
            }
          }
        }
    );
  }
}

