In Flutter, you can use the shared_preferences package to store and retrieve data using shared preferences easily. Shared preferences are a simple way to store key-value pairs persistently across user sessions.
- Add the shared_preferences dependency to your pubspec.yaml file:-
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.0
- Import the shared_preferences package in your Dart file:-
import 'package:shared_preferences/shared_preferences.dart';
3.Storing Data with Shared Preferences:
Future saveData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
// Storing data
prefs.setString('username', 'JohnDoe');
prefs.setInt('age', 30);
prefs.setBool('isLogged', true);
print('Data saved to shared preferences.');
}
4.Retrieving Data from Shared Preferences:
Future loadData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
// Retrieving data
String? username = prefs.getString('username');
int? age = prefs.getInt('age');
bool? isLogged = prefs.getBool('isLogged');
print('Username: $username');
print('Age: $age');
print('Logged in: $isLogged');
}
5.Clearing Data from Shared Preferences:
Future clearData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
// Clearing specific data
prefs.remove('username');
// Clearing all data
// prefs.clear();
print('Data cleared from shared preferences.');
}
Top comments (0)