Debug School

rakesh kumar
rakesh kumar

Posted on

Using SharedPreferences in Flutter to store data locally

What is SharedPreferences in Flutter?
shared_preferences data type
shared_preferences methods
Adding data
Retrieving data
Deleting data
Verifying that data exists
Using shared_preferences in Flutter
Testing our Flutter app
Implementing a splash screen using SharedPreferences
Testing our splash screen

store api data using controller in shared preferene
shared-preferences-in-flutter

What is SharedPreferences in Flutter?

sharedpreferences-in-flutter-to-store-data-locally
SharedPreferences is what Android and iOS apps use to store simple data in an allocated space. T*his data exists even when the app is shut down and starts up again; we can still retrieve the value as it was.*

The data stored in SharedPreferences can be edited and deleted. SharedPreferences stores the data in a key-value pair.

To use SharedPreferences in Flutter, a plugin called shared_preferences enables us to store data. The plugin wraps NSUserDefaults on iOS and SharedPreferences on Android.

Where we can use Shared Preferences

We can use it to store Entered Username and Password locally using Save me button. So there is no need to enter email password each time we login. We can also store app login season cookie in it.

Adding data

It’s possible to add data of primitive types to SharedPreferences. We can add the following primitive types:

int
string
bool
double
Enter fullscreen mode Exit fullscreen mode

Each primitive type has its corresponding setter method. (Note: The key of the key-value pair is in string.)

Add int

prefs.setInt('counter', 1);
Enter fullscreen mode Exit fullscreen mode

This adds an int, 1, to the counter table of SharedPreferences.

Add string

prefs.setString('counter', "yes");
Enter fullscreen mode Exit fullscreen mode

This adds a string, "yes", to the counter.

Add bool

prefs.setBool('counter', true);
Enter fullscreen mode Exit fullscreen mode

This adds a bool, true, to the counter.

Add double

prefs.setDouble('counter', 10.2);
Enter fullscreen mode Exit fullscreen mode

Get int data

int value = prefs.getInt('counter');
The getInt method is used to retrieve an int value from the SharedPreferences
Enter fullscreen mode Exit fullscreen mode

.

value // 1
Get bool data

bool value = prefs.getBool('counter');
This method getBool returns a boolean value from the SharedPreferences.
Enter fullscreen mode Exit fullscreen mode

value // true
Get double data

double value = prefs.getDouble('counter');
The getDouble method returns a double value from the SharedPreferences
Enter fullscreen mode Exit fullscreen mode

.

value // 10.2
Get string data

string value = prefs.getString('counter');
The getString method returns a string value from the SharedPreferences.
Enter fullscreen mode Exit fullscreen mode

value // "yes"
null value
In a case where the data is not present in the SharedPreferences, a null value is returned:

prefs.getInt("_counter")
// null

prefs.getBool("_counter")
// null

prefs.getString("_counter")
// null

prefs.getDouble("_counter")
// null
Enter fullscreen mode Exit fullscreen mode

Deleting data

To remove data from the SharedPreferences, we’ll use the remove method. The key of the data is passed to the .remove method so the key-value pair data in the SharedPreferences is deleted.

prefs.remove("counter");
Enter fullscreen mode Exit fullscreen mode

Here, the counter in the SharedPreferences is deleted.

Verifying that data exists

We can check in SharedPreferences to see whether data exists before we either read or write. To do this, we’ll use the containsKey method.

The containsKey method accepts the key of the data in its arg and uses it to check whether the key exists in SharedPreferences.

The method returns a bool, true or false:

prefs.containsKey("counter")
Enter fullscreen mode Exit fullscreen mode

// true
In the above example, counter exists in the SharedPreferences. That’s why it returns true.

prefs.containsKey("_counter")
// false
Enter fullscreen mode Exit fullscreen mode

_counter does not exist, so it returns false.

Using shared_preferences in Flutter

By default, Flutter adds a counter project whenever you scaffold a new project. This counter project enables us to increment a counter when a FloatingActionButton is pressed. The current state of the counter is displayed as it is being increased.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

The counter reverts to 0 when the app is destroyed or closed. We’ll use SharedPreferences to persist the state of the counter so the counter value begins from where it was before the app was shut down.

Let’s do it.

First, import the shared_preferences plugin:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
Enter fullscreen mode Exit fullscreen mode

Next, add an initState lifecycle method in the MyHomePageState widget. This lifecycle method is called when a stateful widget is being initialized.

Here, we’ll load the counter from SharedPreferences. If present, we’ll make it the counter value. If not, we assign 0 to the counter:

  void loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getInt('counter') ?? 0);
    });
  }

  @override
  void initState() {
    super.initState();
    loadCounter();
  }
Enter fullscreen mode Exit fullscreen mode

Now let’s make the _incrementCounter function an async function. Inside it, we’ll get the counter from SharedPreferences, increment it, then set the counter with the increment and also set the increment in the SharedPreferences.

  void _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = ((prefs.getInt('counter') ?? 0) + 1);
      prefs.setInt('counter', _counter);
    });
  }
Enter fullscreen mode Exit fullscreen mode

Now our Flutter application can remember the last value of the counter when shut down and restarted.

Testing our Flutter app

Write Data in Shared Preferences :-

shared-preferences-in-flutter

// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();

// Save an integer value to 'counter' key. 
await prefs.setInt('counter', 10);
// Save an boolean value to 'repeat' key. 
await prefs.setBool('repeat', true);
// Save an double value to 'decimal' key. 
await prefs.setDouble('decimal', 1.5);
// Save an String value to 'action' key. 
await prefs.setString('action', 'Start');
// Save an list of strings to 'items' key. 
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);
Enter fullscreen mode Exit fullscreen mode

** Obtain shared preferences.**

final prefs = await SharedPreferences.getInstance();

// Save an integer value to 'counter' key. 
await prefs.setInt('counter', 10);
// Save an boolean value to 'repeat' key. 
await prefs.setBool('repeat', true);
// Save an double value to 'decimal' key. 
await prefs.setDouble('decimal', 1.5);
// Save an String value to 'action' key. 
await prefs.setString('action', 'Start');
// Save an list of strings to 'items' key. 
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);
Enter fullscreen mode Exit fullscreen mode

Read Data in Shared Preferences

// Try reading data from the 'counter' key. If it doesn't exist, returns null.
final int? counter = prefs.getInt('counter');
// Try reading data from the 'repeat' key. If it doesn't exist, returns null.
final bool? repeat = prefs.getBool('repeat');
// Try reading data from the 'decimal' key. If it doesn't exist, returns null.
final double? decimal = prefs.getDouble('decimal');
// Try reading data from the 'action' key. If it doesn't exist, returns null.
final String? action = prefs.getString('action');
// Try reading data from the 'items' key. If it doesn't exist, returns null.
final List<String>? items = prefs.getStringList('items');
Enter fullscreen mode Exit fullscreen mode

Try reading data from the 'counter' key

.

If it doesn't exist, returns null.
final int? counter = prefs.getInt('counter');
// Try reading data from the 'repeat' key. If it doesn't exist, returns null.
final bool? repeat = prefs.getBool('repeat');
// Try reading data from the 'decimal' key. If it doesn't exist, returns null.
final double? decimal = prefs.getDouble('decimal');
// Try reading data from the 'action' key. If it doesn't exist, returns null.
final String? action = prefs.getString('action');
// Try reading data from the 'items' key. If it doesn't exist, returns null.
final List<String>? items = prefs.getStringList('items');
Enter fullscreen mode Exit fullscreen mode

Contents in this project Example of Shared Preferences in Flutter to Save Data Locally :-

For Detail click here
click here
click here
click here

Top comments (0)