Shared Preferences - Data Persistence Flutter

Last updated Mar 05, 2020


In This post we are going to learn about Shared Preferences in Flutter

What is SharedPreferences?
SharedPreferences is used for storing data key-value pair in the Android and iOS.
SharedPreferences in flutter uses NSUserDefaultson iOS and SharedPreferences on Android, providing a persistent store for simple data

Let's Start

Step 1: Create Flutter Application

Step 2: Add depemndencies

dependencies:
flutter:
sdk: flutter

shared_preferences: ^0.5.4

Step 3 Create dart file and update below code

import 'package:flutter/material.dart';

import 'package:shared_preferences/shared_preferences.dart';

class MySharedPref extends StatefulWidget{
  @override
  State createState() {
    // TODO: implement createState
    return MySharedPrefState();
  }

}

class MySharedPrefState extends State{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(title: Text("SharedPreference"),backgroundColor: Colors.pink,),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.pink,
          child: Icon(Icons.add),
          onPressed: (){
        _incrementCounter();
      }),
      body: Center(
        child:  FutureBuilder(
          future: _getIncrementCounter(),
          builder:(BuildContext context, AsyncSnapshot snapshot) {
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text("The Incremented Value is ",style: TextStyle(color: Colors.pink,fontSize: 20),),
                SizedBox(height: 20,),
                Text((snapshot.data==null)?"":snapshot.data.toString(),style: TextStyle(color: Colors.pink,fontSize: 20),),
              ],
            );
          },
        ),
      ),
    );
  }


  _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int counter = (prefs.getInt('counter') ?? 0) + 1;
    setState(() {
      prefs.setInt('counter', counter);
    });


  }

  Future_getIncrementCounter() async {

    SharedPreferences prefs = await SharedPreferences.getInstance();
    int counter = (prefs.getInt('counter') ?? 0) + 1;
    return counter;
  }
}

 

Saving String value

addStringValue() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString('stringValue', "abc");
}

 

Saving int value

addIntValue() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setInt('intValue', 123);
}

 

Saving double value

addDoubleValue() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setDouble('doubleValue', 115.0);
}

 

Saving boolean value

addBoolValue() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setBool('boolValue', true);
}

Step 4: Update main dart file

void main() => runApp(MyApp());

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.pink
      ),
      home: MySharedPref(),
    );
  }

}

 

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

614 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions