What are Shared Preferences?
Shared Preferences in Flutter allow you to store key-value pairs of primitive data types. This storage method is perfect for saving small amounts of data, such as user settings or application preferences, that need to persist across sessions but do not require the overhead of a database.
Why Use Shared Preferences?
Using shared preferences in your Flutter app comes with several advantages:
- Simplicity: Easy to implement and use.
- No Database Needed: Avoids the complexity and resource usage of a full database.
- Efficiency: Ideal for storing small amounts of data.
- Persistence: Data remains available across app restarts.
Getting Started with Shared Preferences in Flutter
First, add the shared_preferences package to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.6
Run flutter pub get to install the package.
Basic Usage
Import the Package
To use shared preferences, start by importing the package:
import 'package:shared_preferences/shared_preferences.dart';
Saving Data
Here's a simple function to save a string value:
Future<void> saveStringValue(String key, String value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(key, value);
}
Retrieving Data
To retrieve the stored string value, use:
Future<String?> getStringValue(String key) async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(key);
}
Here is a complete example of code for storing and retrieving data from Shared Preferences:
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(
title: 'Shared Preferences Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _key = "key";
String _value = "value";
@override
void initState() {
super.initState();
_loadSavedValue();
}
// Function to load saved value from SharedPreferences
void _loadSavedValue() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_value = prefs.getString(_key) ?? ""; // Using ?? "" to handle null case
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Shared Preferences Demo"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Value: $_value"),
TextField(
decoration: InputDecoration(
hintText: "Enter value",
),
onChanged: (value) {
setState(() {
_value = value;
});
},
),
RaisedButton(
child: Text("Save"),
onPressed: () {
_saveValue();
},
),
],
),
),
);
}
// Function to save value to SharedPreferences
void _saveValue() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString(_key, _value);
}
}
Top comments (5)
Hey friend, nice post! 👋
did you know you can get syntax highlighting with your codeblocks in markdown? Simply put the language of your choice after the code block declaration, like:
Here's a formatting guide in case you need some help troubleshooting. Best of luck and thanks again for sharing this post!
Thank you for the tip 🙌🙌
Great article! Really helped me out 🙌
Great Post. 🔥