Flutter Shared Preferences, check if first run not working

2.4k Views Asked by At

I was originally following the code for the answer found here:

Check if an application is on its first run with Flutter

And I was incorporating it into the introduction_screen package on pub.dev

I successfully have it loading the page for my onboarding page on first load. Then when I am done with the onboarding page I try to set the shared preference value to 'true' so when I reload the app it will skip the onboarding page, but it does not work when i test in my emulator in VS Code.

I check the value on first book here:

class _MyAppState extends State<MyApp> {
  bool isLoggedIn = false;
  _MyAppState() {
    MySharedPreferences.instance
        .getBooleanValue("isfirstRun")
        .then((value) => setState(() {
              isLoggedIn = value;
            }));
  }

I load the onboarding screen if false here:

    home: isLoggedIn ? MainPage() : OnBoard(),

My Shared Pref dart file is:

import 'package:shared_preferences/shared_preferences.dart';

class MySharedPreferences {
  MySharedPreferences._privateConstructor();

  static final MySharedPreferences instance =
      MySharedPreferences._privateConstructor();
  setBooleanValue(String key, bool value) async {
    SharedPreferences myPrefs = await SharedPreferences.getInstance();
    myPrefs.setBool(key, value);
  }

  Future<bool> getBooleanValue(String key) async {
    SharedPreferences myPrefs = await SharedPreferences.getInstance();
    return myPrefs.getBool(key) ?? false;
  }
}

When the onboarding is complete I run this:

          MySharedPreferences.instance.setBooleanValue("loggedin", true);
          //replace with main page
          Route route = MaterialPageRoute(builder: (context) => MainPage());
          Navigator.pushReplacement(context, route);

If I hot reload in VS everything is ok, but if I restart with the the app it runs the onboarding screen each time.

2

There are 2 best solutions below

1
On

You should check and change the isLoggedIn value in initstate function

For example

  class _MyAppState extends State<MyApp> {
  bool isLoggedIn = false;
  @override
  void initState() {
  MySharedPreferences.instance
      .getBooleanValue("isfirstRun")
      .then((value) => setState(() {
  isLoggedIn = value;
  }));
  super.initState();

  }


  @override
  Widget build(BuildContext context) {
  return Something...
  }


    
8
On

Use async and await in a separate function and then use it in initState:

  void verityFirstRun() async {

    final verification = await SharedPreferences.getInstance();

    isLoggedIn = verification.getBool("isfirstRun") ?? false;

  }

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

Use this way of calling the SharedPreferences instance:

final verification = await SharedPreferences.getInstance();