Getting Started with Shared Preferences in Flutter
Introduction
When developing mobile applications, it’s often necessary to store simple data persistently, such as user preferences or app settings. In Flutter, one of the most straightforward ways to achieve this is by using the shared_preferences
package. This package allows you to store data locally on the device in a key-value format. In this post, we’ll walk through how to integrate shared_preferences
into a Flutter app, covering the essential functions for storing, retrieving, and removing data.
Setting Up shared_preferences
Before diving into the code, you need to include the shared_preferences
package in your Flutter project. Here's how you can do it:
- Add Dependency
Open your pubspec.yaml
file and add shared_preferences
under dependencies:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.15
Run flutter pub get
in your terminal to install the package.
- Import the Package
In your Dart file where you want to use shared preferences, import the package:
import 'package:shared_preferences/shared_preferences.dart';
Implementing Shared Preferences
Here’s a complete example of how to use shared_preferences
to store, retrieve, and remove data in a Flutter application.
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: PreferencesPage(),
);
}
}
class PreferencesPage extends StatefulWidget {
@override
_PreferencesPageState createState() => _PreferencesPageState();
}
class _PreferencesPageState extends State<PreferencesPage> {
final TextEditingController _controller = TextEditingController();
String _savedValue = "";
@override
void initState() {
super.initState();
_loadSavedValue();
}
Future<void> _loadSavedValue() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_savedValue = prefs.getString('saved_key') ?? "No value saved yet.";
});
}
Future<void> _saveValue() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('saved_key', _controller.text);
_loadSavedValue();
}
Future<void> _removeValue() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.remove('saved_key');
_loadSavedValue();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Shared Preferences Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _controller,
decoration: InputDecoration(labelText: 'Enter value to save'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _saveValue,
child: Text('Save Value'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _removeValue,
child: Text('Remove Value'),
),
SizedBox(height: 20),
Text('Saved Value: $_savedValue'),
],
),
),
);
}
}
Code Explanation
- Initialization:
SharedPreferences.getInstance()
retrieves the shared preferences instance, allowing you to access persistent storage. - Storing Data: Use
prefs.setString('key', 'value')
to save a string value. For integers, doubles, and booleans, usesetInt()
,setDouble()
, andsetBool()
respectively. - Retrieving Data: Fetch stored data with
prefs.getString('key')
. Similarly, usegetInt()
,getDouble()
, andgetBool()
for other types. - Removing Data: Remove stored data using
prefs.remove('key')
. - Updating UI: The
_loadSavedValue()
method reloads data from shared preferences and updates the UI to reflect changes.
Conclusion
The shared_preferences
package is a powerful tool for managing simple, persistent data in Flutter apps. Whether you need to save user settings, preferences, or small pieces of data, this package provides a straightforward and effective solution. With the basics covered, you can now integrate shared_preferences
into your own Flutter projects to enhance user experience by preserving important data.
Feel free to experiment with different data types and use cases to fully leverage the capabilities of shared_preferences
. Happy coding!