close
How To Store And Get Data From Shared Preferences in Flutter

How To Store And Get Data From Shared Preferences in Flutter

Hello Guys How are you all? Hope you all are fine. Today We are going to learn How To Store And Get Data From Shared Preferences in Flutter?

We have to store some offline data to our storage and get them back while we want in shared preferences in flutter. In This tutorial very simple way I am going to explain How To Store And Get Data From Shared Preferences in Flutter. So lets start this tutorial.

How To Store And Get Data From Shared Preferences in Flutter

How To Store And Get Data From Shared Preferences in Flutter

  • We are going to use flutter package for shared preferences.
  • define shared_preferences package in pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^0.5.12
  • Then make StorageUtil.dart file in your lib folder.
  • Then after import shared_preference package in our file.
import 'package:shared_preferences/shared_preferences.dart';
  • Make class named StorageUtil in StorageUtil.dart file.
  • After that, define StorageUtil and SharedPreferences variables.
class StorageUtil {
  static StorageUtil _storageUtil;
  static SharedPreferences _preferences;
}
  • Actually Shared Preference is using async and await method. so it will use Future to put and get from Shared preference.
  • Make getInstance method to get Storage and set this method to init so it will init every time.
  static Future<StorageUtil> getInstance() async {
    if (_storageUtil == null) {
      var secureStorage = StorageUtil._();
      await secureStorage._init();
      _storageUtil = secureStorage;
    }
    return _storageUtil;
  }

  StorageUtil._();
  Future _init() async {
    _preferences = await SharedPreferences.getInstance();
  }
  • Then I Have Created Method to put data into Preference. so you can use this method.
  // put string
  static Future<bool> putString(String key, String value) {
    if (_preferences == null) return null;
    return _preferences.setString(key, value);
  }
  • I have also created method to get data from Preference.
  // get string
  static String getString(String key, {String defValue = ''}) {
    if (_preferences == null) return defValue;
    return _preferences.getString(key) ?? defValue;
  }
  • Also I Have Method that will clear data from Preference.
  // clear string
  static Future<bool> clrString() {
    SharedPreferences prefs = _preferences;
    prefs.clear();
  }
  • Now, Our StorageUtil.dart is Ready. Lets move to our main.dart file.
  • First of all lets import StorageUtil.dart and material.dart in our main.dart file.
import 'package:flutter/material.dart';
import 'package:flutter_app_test/StorageUtills.dart';
  • Then, make main void method. But Wait for one minute. We have to initialize our StorageUtil In our main void method.
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await StorageUtil.getInstance();
  runApp(SharedPreference());
}
  • Then make StatefulWidget class named *SharedPreference* that we define in runApp.
class SharedPreference extends StatefulWidget {
  @override
  _SharedPreferenceState createState() => _SharedPreferenceState();
}

class _SharedPreferenceState extends State<SharedPreference> {

}
  • Now, when ever you want to set data into your Preference then just paste this code.
StorageUtil.putString("key_name", "This is Key Value");
  • In Above line there is first value is our key that we will use to store and receive data. and second one is key value.
  • Now, how to get key value ? Its also very simple. Just Paste this code where ever you want value.
StorageUtil.getString("key_name");
  • just define key_name. It will return value.
  • Here is my main.dart file Source.
import 'package:flutter/material.dart';
import 'package:flutter_app_test/StorageUtills.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await StorageUtil.getInstance();
  runApp(SharedPreference());
}

class SharedPreference extends StatefulWidget {
  @override
  _SharedPreferenceState createState() => _SharedPreferenceState();
}

class _SharedPreferenceState extends State<SharedPreference> {
  String savedString = "Here will Preference Value";

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('Shared Preferences - FlutterCorner'),
        ),
        body: Center(
          child: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  savedString,
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 16,
                  ),
                ),
                RaisedButton(
                  onPressed: () {
                    StorageUtil.putString("key_name", "This is Key Value");
                  },
                  textColor: Colors.white,
                  color: Colors.green,
                  padding: EdgeInsets.all(8.0),
                  child: Text(
                    "Save Data",
                  ),
                ),
                RaisedButton(
                  onPressed: () {
                    setState(() {
                      savedString = StorageUtil.getString("key_name");
                    });
                  },
                  textColor: Colors.white,
                  color: Colors.green,
                  padding: EdgeInsets.all(8.0),
                  child: Text(
                    "Get Data",
                  ),
                ),
                RaisedButton(
                  onPressed: () {
                    setState(() {
                      StorageUtil.clrString();
                      savedString = StorageUtil.getString("key_name");
                    });
                  },
                  textColor: Colors.white,
                  color: Colors.green,
                  padding: EdgeInsets.all(8.0),
                  child: Text(
                    "Clear Data",
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
  • Here is my StorageUtills.dart File Code
import 'package:shared_preferences/shared_preferences.dart';

class StorageUtil {
  static StorageUtil _storageUtil;
  static SharedPreferences _preferences;

  static Future<StorageUtil> getInstance() async {
    if (_storageUtil == null) {
      var secureStorage = StorageUtil._();
      await secureStorage._init();
      _storageUtil = secureStorage;
    }
    return _storageUtil;
  }

  StorageUtil._();
  Future _init() async {
    _preferences = await SharedPreferences.getInstance();
  }

  // get string
  static String getString(String key, {String defValue = ''}) {
    if (_preferences == null) return defValue;
    return _preferences.getString(key) ?? defValue;
  }

  // put string
  static Future<bool> putString(String key, String value) {
    if (_preferences == null) return null;
    return _preferences.setString(key, value);
  }

  // clear string
  static Future<bool> clrString() {
    SharedPreferences prefs = _preferences;
    prefs.clear();
  }
}

Faq

  1. How To Store And Get Data From Shared Preferences in Flutter

    To Store And Get Data From Shared Preferences in Flutter
    We are going to use flutter package for shared preferences.
    define shared_preferences package in pubspec.yaml file.
    Then make StorageUtil.dart file in your lib folder.
    Then after import shared_preference package in our file.
    Make class named StorageUtil in StorageUtil.dart file.
    After that, define StorageUtil and SharedPreferences variables.
    Actually Shared Preference is using async and await method. so it will use Future to put and get from Shared preference.
    Make getInstance method to get Storage and set this method to init so it will init every time.
    Then I Have Created Method to put data into Preference. so you can use this method.
    I have also created method to get data from Preference.

  2. Store And Get Data From Shared Preferences in Flutter

    To Store And Get Data From Shared Preferences in Flutter
    We are going to use flutter package for shared preferences.
    define shared_preferences package in pubspec.yaml file.
    Then make StorageUtil.dart file in your lib folder.
    Then after import shared_preference package in our file.
    Make class named StorageUtil in StorageUtil.dart file.
    After that, define StorageUtil and SharedPreferences variables.
    Actually Shared Preference is using async and await method. so it will use Future to put and get from Shared preference.
    Make getInstance method to get Storage and set this method to init so it will init every time.
    Then I Have Created Method to put data into Preference. so you can use this method.
    I have also created method to get data from Preference.

Summery

So Guys That’s It For How To Store And Get Data From Shared Preferences in Flutter. Hope you like our tutorial. Comment below Your thoughts and your queries. And Also Comment below your suggestion here.

Also Check Out Below Tutorials

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *