Shared Preferences in Flutter is a simple way to store small amounts of data persistently. This is particularly useful for storing user preferences, settings, or any other small data that needs to be retained across app launches.
Key Concepts
- SharedPreferences Package: A Flutter plugin that provides a persistent storage mechanism for simple data.
- Key-Value Storage: Data is stored as key-value pairs, similar to a dictionary.
- Data Types Supported: Shared Preferences support basic data types like
int,double,bool,String, andList<String>.
Setting Up Shared Preferences
Step 1: Add Dependency
First, add the shared_preferences package to your pubspec.yaml file:
Run flutter pub get to install the package.
Step 2: Import the Package
Import the shared_preferences package in your Dart file:
Using Shared Preferences
Saving Data
To save data, you need to get an instance of SharedPreferences and then use the appropriate setter method.
Future<void> saveData() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('counter', 10);
await prefs.setString('username', 'JohnDoe');
await prefs.setBool('isLoggedIn', true);
}Reading Data
To read data, you also need to get an instance of SharedPreferences and then use the appropriate getter method.
Future<void> readData() async {
final prefs = await SharedPreferences.getInstance();
int counter = prefs.getInt('counter') ?? 0;
String username = prefs.getString('username') ?? 'Guest';
bool isLoggedIn = prefs.getBool('isLoggedIn') ?? false;
print('Counter: $counter');
print('Username: $username');
print('Is Logged In: $isLoggedIn');
}Removing Data
To remove data, use the remove method with the key of the data you want to delete.
Future<void> removeData() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('counter');
}Practical Example
Let's create a simple Flutter app that uses Shared Preferences to store and retrieve a counter value.
Step 1: Create a New Flutter Project
Step 2: Update pubspec.yaml
Add the shared_preferences dependency:
Step 3: Update main.dart
Replace the content of lib/main.dart with the following code:
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: CounterScreen(),
);
}
}
class CounterScreen extends StatefulWidget {
@override
_CounterScreenState createState() => _CounterScreenState();
}
class _CounterScreenState extends State<CounterScreen> {
int _counter = 0;
@override
void initState() {
super.initState();
_loadCounter();
}
// Load counter value from SharedPreferences
Future<void> _loadCounter() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_counter = prefs.getInt('counter') ?? 0;
});
}
// Increment counter and save to SharedPreferences
Future<void> _incrementCounter() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_counter++;
});
await prefs.setInt('counter', _counter);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Shared Preferences Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}Step 4: Run the App
Run the app using flutter run. You should see a counter that increments each time you press the floating action button. The counter value is saved using Shared Preferences and will persist across app launches.
Exercises
Exercise 1: Save User Preferences
Create a form that allows users to save their name and email. Use Shared Preferences to persist this data.
Solution:
- Add text fields for name and email.
- Save the data using Shared Preferences when the user submits the form.
- Load the data when the form is initialized.
Exercise 2: Theme Preference
Add a toggle switch to enable dark mode. Save the user's preference using Shared Preferences and apply the theme accordingly.
Solution:
- Add a switch to toggle between light and dark themes.
- Save the theme preference using Shared Preferences.
- Load the theme preference when the app starts and apply the theme.
Common Mistakes and Tips
- Forgetting to await: Always use
awaitwhen calling methods onSharedPreferencesto ensure the data is saved or loaded correctly. - Null Safety: Always provide a default value when reading data to handle cases where the key might not exist.
Conclusion
In this section, you learned how to use Shared Preferences in Flutter to store and retrieve small amounts of data persistently. This is a powerful tool for saving user settings, preferences, and other small pieces of data that need to be retained across app launches. In the next section, we will explore file storage for handling larger amounts of data.
