Shared Preferences Package in Flutter
Flutter utilizes the Shared Preferences package to store and persist user data. Shared Preferences is a package used to store small pieces of data as key-value pairs. It is commonly employed to store user preferences, session states, and similar data.
Getting started with the Shared Preferences package in Flutter is straightforward. First, you need to add the shared_preferences
package to your pubspec.yaml
file. You can include the package in your project by adding the following line to the dependencies
section:
dependencies:
shared_preferences: ^2.0.0
Once the package is added to your project, you can use the SharedPreferences
class to store and retrieve data.
To store data, you can use the getInstance
method of the SharedPreferences class. For example:
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('username', 'JohnDoe');
prefs.setInt('age', 25);
prefs.setBool('isLogged', true);
}
In this example, an instance of SharedPreferences is obtained, and the setString
, setInt
, and setBool
methods are used to store the values of the username, age, and login status, respectively.
To retrieve data, you can use the corresponding get
methods of the SharedPreferences class. For example:
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String username = prefs.getString('username');
int age = prefs.getInt('age');
bool isLogged = prefs.getBool('isLogged');
print('Username: $username');
print('Age: $age');
print('Is Logged: $isLogged');
}
This code snippet retrieves the username, age, and login status from the SharedPreferences instance and prints them to the console.
The Shared Preferences package is a handy tool for storing user data in a simple manner. However, it is not suitable for large datasets as it is designed for storing small data fragments. For larger datasets, it is recommended to use SQLite or other database solutions.