To store some simple data persistently, you can use the shared_preferences plugin. Data has persisted to disk asynchronously so you need to use Future, async, await. If you aren’t familiar with them, check this guide.
Overview
Below are the most commonly used methods provided by package shared_preferences:
Writing data
- setString(String key, String value)
- setInt(String key, int value):
- setDouble(String key, double value)
- setStringList(String key, List value)
- setBool(String key, bool value)
Reading data
- getString(String key)
- getInt(String key)
- getDouble(String key)
- getStringList(String key)
- getBool(String key)
- containsKey(String key): Check whether key exists or not
Deleting data
- remove(String key)
- clear(): Remove any saved data
Complete Example
We’ll make a small Flutter application that lets the user enter his/her name and save it locally. When the app starts next time, it’ll display a text like this:
Hello [saved name]
Our app also has a button to reset the saved data (this button only shows up if it has saved data).
1. Install shared_preferences by executing the following:
flutter pub add shared_preferences
Then run this command:
flutter pub get
2. The complete code in main.dart:
// kindacode.com
// main.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
// Hide the debug banner
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String? _savedName;
final TextEditingController _nameController = TextEditingController();
// Retrieve the saved name if it exists
@override
void initState() {
super.initState();
_retrieveName();
}
Future<void> _retrieveName() async {
final prefs = await SharedPreferences.getInstance();
// Check where the name is saved before or not
if (!prefs.containsKey('name')) {
return;
}
setState(() {
_savedName = prefs.getString('name');
});
}
// this function will save the name to the shared preferences
Future<void> _saveName() async {
final prefs = await SharedPreferences.getInstance();
prefs.setString('name', _nameController.text);
}
// this function will clear the name from the shared preferences
Future<void> _clearName() async {
final prefs = await SharedPreferences.getInstance();
// Check where the name is saved before or not
if (!prefs.containsKey('name')) {
return;
}
await prefs.remove('name');
setState(() {
_savedName = null;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Kindacode.com'),
),
body: Padding(
padding: const EdgeInsets.all(25),
child: _savedName == null
? Column(
children: [
TextField(
controller: _nameController,
decoration:
const InputDecoration(labelText: 'Your Name'),
),
ElevatedButton(
onPressed: _saveName, child: const Text('Save'))
],
)
: Column(children: [
Text(
'Hello $_savedName',
style: const TextStyle(fontSize: 50),
),
ElevatedButton(
onPressed: _clearName, child: const Text('Reset'))
])));
}
}
Check our app:
Conclusion
We’ve walked through the fundamentals of shared_preferences and examined a complete example of using it in practice. There are other approaches to save data offline in Flutter. For more details, take a look at the following articles:
- Flutter & SQLite: CRUD Example
- Flutter & Hive Database: CRUD Example
- Flutter: Load and display content from CSV files
- Flutter: How to Read and Write Text Files
- How to read data from local JSON files in Flutter
- Ways to Store Data Offline in Flutter
You can also check out our Flutter topic page or Dart topic page to see the latest tutorials and examples.