Open In App

Read and Write Data in Flutter using SharedPreferences

Last Updated : 08 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

add Plugin

 

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.

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

Create a project and Import the material package.

Dart




import 'package:flutter/material.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 create the class MyHomePage, where we can display the actual data.

Dart




import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.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.

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads