Search code examples
fluttercountwidgetsharedpreferences

Count how many times the app is open using shared preferences


I have a widget who should be shown on home screen after a number of app open events. I know I have to use shared preferences, but I don't know how to implement it.


Solution

  • int value = 0; // when app open event call get the int to check last time value value.

    value = prefs.getInt("key") ?? 0 : prefs.getInt("key");

    // when app open event call set the int with appended value.

    SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setInt("key",(value + 1));

    // when you want to check that how many time app opens you can use this.

    SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.getInt("key");