Adding Shared Preferences To App4

  1. Installing
  2. Run this command:

    flutter pub add shared_preferences

    This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

    dependencies:
         shared_preferences: ^2.0.9

    Or visit shared_preferences - pub.dev

    Now run pub get from the command line:

    flutter pub get

    You’re now ready to store data.


  3. Import the package in the main

  4. import 'package:shared_preferences/shared_preferences.dart';




  5. Create a key
  6. All preferences need to use a unique key or they’ll be overwritten. Here, you’re simply defining a constant for the preference key.

     static const String bestScorekey = 'bestScore';



  7. Saving The Best Score
  8. To understand the code you’ll add next, you need to know a bit about running code in the background.

    Most modern UIs have a main thread that runs the UI code. Any code that takes a long time needs to run on a different thread or process so it doesn’t block the UI.
    Dart uses a technique similar to JavaScript to achieve this. The language includes these two keywords:

    • async
    • await

    Check these lessons :

         Handling Futures

         Declaring async funtions

      void saveNewBestScore(int value) async {

        //1

        final prefs = await SharedPreferences.getInstance();

        //2

        prefs.setInt(bestScorekey, value);

      }




    Here, you use the async keyword to indicate that this method will run asynchronously. It also:

    1. Uses the await keyword to wait for an instance of SharedPreferences.

    2. Saves the best score using the prefSearchKey key.

    Next, call it in the check answer method:

      void checkAnswer() {

        if (answer == correctCountry) {

          setState(() {

            score++;

            prepareCountries();

          });

        } else {

          if (score > bestScore) {

            bestScore = score;

            ///add this here

            saveNewBestScore(score);

          }

     

          setState(() {

            playing = false;

          });

          prepareCountries();

        }

      }




  9. Getting The Best Score

  10.   void getBestScore() async {

        //1

        final prefs = await SharedPreferences.getInstance();

        //2

        if (prefs.containsKey(bestScorekey)) {

          //3

          bestScore = prefs.getInt(bestScorekey);

        }

      }




    This method is also asynchronous. Here, you:

    1. Use the await keyword to wait for an instance of SharedPreferences.

    2. Check if a preference for the best score already exists.

    3. Get the best score.


    Finally, right after super.initState() in initState() call it:

      @override

      void initState() {

        super.initState();

        prepareCountries();

        getBestScore();

      }




    This loads the previous best score when the user restarts the app.



  11. Test the app



  12. Code Source


  13. github