What is SharedPreference in Flutter?
What exactly is SharedPreferences?
In Android and iOS, SharedPreferences is used to store data key-value pairs. NSUserDefaults on iOS and SharedPreferences on Android are used by SharedPreferences in flutter to provide a permanent storage for basic data. You can grab more about SharedPreferences from the top training institutes for Flutter in Kochi.
How to add SharedPreferences in Flutter
Step 1:
Add dependency
dependencies:
flutter:
sdk: flutter
shared_preferences: “<the latest version>”
Step 2:
Import SharedPreferences to main. dart file
import ‘package:shared_preferences/shared_preferences.dart’;
Step 3: Store data.
Using SharedPreferences, we can only add int, String, double, and bool values. The SharedPreferences class contains setter methods that take two parameters, key and value.
Note: Keys allows only string values
Step 4: Fetch data
When accessing data from the store using SharedPreferences, we simply need to pass the key. If the value is not found in the storage, we may obtain a null value.
Step 5: Delete data
To delete the data from the storage, we use the remove (String key) function.
How wrap SharedPreferences with Platforms
Wraps platform-specific persistent storage for fundamental data (NSUserDefaults on iOS and macOS, SharedPreferences on Android, etc.). Because there is no guarantee that changes will be persisted to disk after returning, this plugin should not be used to save essential data. Data types available are int, double, bool, String, and List<String>.
How to read or retrieve data from SharedPreferences in Flutter?
To obtain or read data from sharedpreferences in flutter, we must utilize the sharedpreferences class’s getter methods. The sharedpreferences class contains five getter methods. We must give only the key, which is a string, to the getter method. The method will return the value of the associated key.
The getter methods of the sharedpreferences class are as follows:
- getSring()
- getInt()
- getDouble()
- getBool()
- getStringList()
We can obtain null as a value when retrieving or reading data from sharedpreferences. If the value for the specified key does not exist or if we provide the incorrect key, it will return null. It will generate an error. This may be solved by using ‘if null’ (??).
These all about Flutter SharedPreferences for Android and iOS. You can choose a Flutter training in Kochi to know more about Flutter internal storage and build your bright future in mobile app development.