Read and Write Data in Flutter using SharedPreferences
Last Updated :
11 Oct, 2024
SharedPreferences is the best option to store a small amount of data in flutter projects. Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, integer, float, Boolean that make up your preferences in an XML file inside the app on the device storage. For example - Storing the username and login status in the shared_preferences. In Android Application consider a case when the user login or not, we can store the state of login- logout in the shared_preferences, so that the user does not need to write a password, again and again, we can save the login state in bool variable it is a small amount of data there is no need of a database, we can store it in shared_preferences to access it fast.
Installation
To use this plugin, add shared_preferences as a dependency in your pubspec.yaml file.
dependencies:
shared_preferences:
Run flutter pub get to install the dependencies.
Note: To Install and Setup SharedPreferences in Flutter you may refer to the following articles:
Examples
Here are some examples to show how to use the shared_preferences.
Note : You can run the same app in web as well as in mobile.
Write Data
// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();
// Save an integer value to 'num' key.
await prefs.setInt('num', 10);
// Save an boolean value to 'flag' key.
await prefs.setBool('flag', true);
// Save an double value to 'decnum' key.
await prefs.setDouble('decnum', 1.5);
// Save an String value to 'name' key.
await prefs.setString('name', 'Start');
// Save an list of strings to 'items' key.
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);
Read Data
// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();
// get an integer value from 'num' key.
await prefs.getInt('num');
// get an boolean value from 'flag' key.
await prefs.getBool('flag');
// get an double value from 'decnum' key.
await prefs.getDouble('decnum');
// get an String value from 'name' key.
await prefs.getString('name');
// get an list of strings from 'items' key.
await prefs.getStringList('items');
Delete Data
// Remove data for the 'counter' key.
final success = await prefs.remove('counter');
Example Project
Open your terminal and create a new Flutter project by running the following command:
flutter create example
Navigate to the project directory:
cd example
Project Directory structure:
Before diving into the code, let's take a look at the directory structure of our project:
Open main.dart file :
Dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
Now in void main( ) function call the runApp( ) method and call the class SharedHome( ).
Dart
void main(){
runApp(SharedHome());
}
Now create a new class named as SharedHome( ) this will be going to be a stateful class because our application does change its state at run time. And return MaterialApp( ).
Dart
class SharedHome extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
_SharedHomeState createState() => _SharedHomeState();
}
class _SharedHomeState extends State<SharedHome> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "SharedPreferences",
theme: ThemeData(primarySwatch: Colors.deepOrange),
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
Now we have to define our HomeScreen( ). Before going to create HomePage,
Let's create another file service.dart.
Dart
import 'package:shared_preferences/shared_preferences.dart';
class Helper {
static String valueSharedPreferences = '';
// Write DATA
static Future<bool> saveUserData(value) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
return await sharedPreferences.setInt(valueSharedPreferences, value);
}
// Read Data
static Future getUserData() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
return sharedPreferences.getInt(valueSharedPreferences);
}
}
In class Helper, we have a static data member valueSharedPreferences, member function saveUserData, and getUserData. In saverUserData function first, we get the instance of the shared_preferences, Then using this Instance we call the method setInt() which basically set the integer value to our static member. In getUserData() function first, we get the instance to shared_preferences. Then return the value of valueSharedPreferences.
Now return back to main.dart file and create the class MyHomePage, where we can display the actual data.
Dart
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
@override
void initState() {
super.initState();
_loadCounter();
}
// Loading counter value on start
void _loadCounter() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0);
});
}
// Incrementing counter after click
void _incrementCounter() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0) + 1;
prefs.setInt('counter', _counter);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Shared Preferences")),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes
// auto-formatting nicer for build methods.
);
}
}
We have two functions loadCounter and incrementCounter. In loadCounter we retrieve the data from the SharedPreferences. In incrementCounter we just increment the value when we press the floating action button and pass it as the parameter to save in SharedPreferences.
Complete Application Code
main.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main(){
runApp(SharedHome());
}
class SharedHome extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
_SharedHomeState createState() => _SharedHomeState();
}
class _SharedHomeState extends State<SharedHome> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "SharedPreferences",
theme: ThemeData(primarySwatch: Colors.deepOrange),
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
@override
void initState() {
super.initState();
_loadCounter();
}
// Loading counter value on start
void _loadCounter() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0);
});
}
// Incrementing counter after click
void _incrementCounter() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0) + 1;
prefs.setInt('counter', _counter);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Shared Preferences")),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes
// auto-formatting nicer for build methods.
);
}
}
Running the App
Save all the files and ensure that your project is correctly set up.
Run the app in the terminal:
flutter run
This will launch the app and the Counter app will show up.
Output:
Similar Reads
How to Setup SharedPreferences in Flutter?
SharedPreferences is a package that enables the Application to store a small amount of data in your local storage. Like user name, id, etc. You don't need other databases for it like SQLITE, FIREBASE, etc. So in this article, we will see How to install the Shared Preferences package in Dart/Flutter
1 min read
Shared Preferences in Flutter
Shared Preferences are a way of storing small information inside the application space. Storing small amounts of data within an application is a common requirement for modern apps. Whether it's tracking user authentication, saving settings, or preserving user preferences, maintaining data between se
10 min read
Flutter - Read and Write Data on Firebase
Firebase helps developers to manage their mobile apps easily. It is a service provided by Google. Firebase has various functionalities available to help developers manage and grow their mobile apps. In this article, we will learn how to write and read data into/from Firebase. Follow the 3-step proce
4 min read
Persist Data with SQLite in Flutter
SQLite is an open-source computer database, it's wont to store a piece of information, perform completely different operations like add, delete, and update. SQLite doesn't need a server or backend code; all the info is saved to a computer file within the device, or we can say it's native to storage.
7 min read
Flutter - Shared Preferences to Keep User Logged In
If you implement Sign-in and Sign-out features in your Android Application. Then you must need the user logged in if the user previously logged in and the user logged out if the user is previously logged-out. So we are in this article implementing How to use shared preferences to logged-in to the us
5 min read
Flutter - Pass Data One Screen To Another Screen
In this article we gonna know how you can pass the data from one screen to another screen in Flutter. In this example we took two screens one and screen two, In the first screen, you enter the data, and that data you can see on your second screen. This is the main object of this application. If we t
4 min read
Flutter - Sending Data To The Internet
Interacting with the Internet is crucial for most apps to function. In Flutter, sending data to the internet is one of them, and the http package is used to send the data to the internet. In this article, we will explore the same topic in detail. Steps to Implement Sending Data to the InternetStep 1
5 min read
How to Install Shared Preferences in Flutter?
Shared preferences in flutter applications are used to store data in Local Storage. Shared Preferences store the data in a key-value pair. and we can also get data in a key-value pair using inbuilt functions. We can save large data in local storage or our Phone storage with the help of SQLite databa
2 min read
Flutter - Send Data to Screen
Interaction with the UI is an integral part of any application. But more often than not, the information needs to be sent from one screen to another. For instance, say you need to pass data regarding a selected or tapped component of the UI to another route(i.e., page). In this article, we will expl
4 min read
Upload and Retrieve Images on MongoDB using Dart in Flutter
To upload files from a local system to the dedicated server is called file uploading and retrieval files from the dedicated server to a local system is called file retrieving. Â It works exactly the same as the definition when we select a file from the Android device and click the submit button, the
6 min read