In this recipe, we will create an app that stores the number of times the app itself has been opened. While the logic of the app is extremely simple, this is useful when you need to keep track of the usage of your app or need to send targeted messages to specific users. In doing so, you will learn how to use the shared_preferences library. Follow these steps:
- First, we must add a dependency to shared_preferences. Go to https://pub.dev/packages/shared_preferences/install and check the latest version of the library.
- In the pubspec.yaml file of your project, add the shared_preferences dependency (with the version number you retrieved in step 1):
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.5
- If necessary, run the flutter pub get command from your Terminal window.
- At the top of the main.dart file, import shared_preferences:
import 'package:shared_preferences/shared_preferences.dart';
- At the top of the _MyHomePageState class, create...