Search code examples
dartfluttersplash-screen

splash screen and one time intro in flutter


I want my splash screen to always appear in my application and it does which is great, but I have a walk through after the splash screen and I want it to be a one time walk through, So i want to add an integer to the shared preferences with a value of 0 and everytime I open the splash screen the value is incremented by one, so when "number" equals 1 or greater at the second run the splash screen skips the walkthrough and goes to home , here is the code that I want to edit now :

void initState() {
    // TODO: implement initState
    super.initState();
    Timer(Duration(seconds: 5), () => MyNavigator.goToIntro(context));
}

And I want it to be like :

void initState() {
    // TODO: implement initState
    super.initState();int number=0;//this is in the shared prefs
    Timer(Duration(seconds: 5), () => if(number==0){MyNavigator.goToIntro(context));
    }else{MyNavigator.goToHome(context));
    number++;}
}

Solution

  • The below code prints perfectly as we expect(during first launch only, "First launch"). You can use your navigation logic instead of print.

    @override
    void initState() {
        super.initState();
        setValue();
    }
    
    void setValue() async {
        final prefs = await SharedPreferences.getInstance();
        int launchCount = prefs.getInt('counter') ?? 0;
        prefs.setInt('counter', launchCount + 1);
        if (launchCount == 0) {
            print("first launch"); //setState to refresh or move to some other page
        } else {
            print("Not first launch");
        }
    }