Open In App

Read and Write Data in Flutter using SharedPreferences

Last Updated : 11 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
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.

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:

gfg_directory


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:


Next Article
Article Tags :

Similar Reads