X

Flutter SharedPreferences Tutorial for Beginners

Flutter SharedPreferences :

Flutter sharedpreferences is a light weight data storage option available in device for storing user details or any other data for processing data within the app.

SharedPreferences store data in the form of Key-Value pairs.Storage, retrieval, update and clear of data is dependent on the key value specified.

In iOS data is stored using NSUserDefaults which acts similar to that of shared preferences in android, as flutter supports both android and iOS devices we can use shared preferences in iOS devices too.

Data can be stored in terms of String, Integers, List, Boolean, Double and also fetch in accordingly.

Also data stored using SharedPreferences is safe as it can be accessible from within the app and cannot be accessed from out side of the app i.e., from another app unless or until the device is rooted.

In the previous tutorial we have seen a example of storing user login credentials may find the link below

 

In this part of the tutorial on flutter sharedpreferences we will be dealing with the storage of data of different data types.

 

Flutter sharedpreferences video tutorial :

Go through the below tutorial for more details.

 

pubspec.yaml :

Add shared preferences to the dependency’s and update the version accordingly.

dev_dependencies:
  flutter_test:
    sdk: flutter
  shared_preferences: 2.0.8

 

main.dart :

Initialize void main()

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

 

Class MyApp extends StatelessWidget

 

Declare SharedPreferences object

late SharedPreferences prefs;

and initialize it we can also declare globally using a constant class so that it can be accessible from any where in the app.

static Future init() async {
  prefs = await SharedPreferences.getInstance();
}

 

class MyApp extends StatelessWidget {

  static Future init() async {
    prefs = await SharedPreferences.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),
    );
  }
}

 

Now try to store a int value in the SharedPreferences in the following key value pair.

prefs.setInt('int', 10);

 

And later we can fetch the above value as by passing the appropriate key value.

final myInt = prefs.getInt('int') ?? 0;

If value is not specified then default value ‘0’ is returned.

 

Also different data types like String, List, Boolean, Double are stored as

 

prefs.setString('string', "Abhi");

prefs.setDouble('double', 3.14);

prefs.setBool('boolean', true);

prefs.setStringList('stringlist', ['horse', 'cow', 'sheep']);

 

And retrieved as below according to their key values.

final myDouble = prefs.getDouble('double') ?? 0.0;

final myBool = prefs.getBool('boolean') ?? false;

final myString = prefs.getString('string') ?? '';

final myStringList = prefs.getStringList('stringlist') ?? [];

 

We can check weather the values are stored by printing these values after fetching them as below

log("\n Int  - $myInt \n double - $myDouble \n boolean - $myBool \n string - $myString \n stringlist - $myStringList");

 

Also clear the values based on the ‘ key

prefs.remove('int');

 

Flutter sharedpreferences FullCode :

Complete code for integration of flutter sharedpreferences is provided below

import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter_sharedpref_basics/SharedPreferences.dart';

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

late SharedPreferences prefs;

class MyApp extends StatelessWidget {

  static Future init() async {
    prefs = await SharedPreferences.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text("Shared Preferences Storage, Retrieval & Clear",
                style: TextStyle(fontSize: 15,color: Colors.brown,fontWeight: FontWeight.bold),),
              SizedBox(height: 50,),
              RaisedButton(child: Text("Save Data"), onPressed: save),
              RaisedButton(child: Text("Fetch Data"),onPressed: fetch),
              RaisedButton(child: Text("Clear Data"),onPressed: remove)
            ],
          ),
        ),
      ),
    );
  }
}

save() async {
  await MyApp.init();

  prefs.setInt('int', 10);

  prefs.setString('string', "Abhi");

  prefs.setDouble('double', 3.14);

  prefs.setBool('boolean', true);

  prefs.setStringList('stringlist', ['horse', 'cow', 'sheep']);
}

fetch() async {
  final myInt = prefs.getInt('int') ?? 0;

  final myDouble = prefs.getDouble('double') ?? 0.0;

  final myBool = prefs.getBool('boolean') ?? false;

  final myString = prefs.getString('string') ?? '';

  final myStringList = prefs.getStringList('stringlist') ?? [];

  log("\n Int  - $myInt \n double - $myDouble \n boolean - $myBool \n string - $myString \n stringlist - $myStringList");
}

remove() async {
  prefs.remove('int');
}

 

Flutter sharedpreferences Output :

This screen depicts the usage of flutter sharedpreferences in your app

 

 

 

abhishek:
Related Post

This website uses cookies.