How to use Flutter Shared Preferences Plugin

I’ll let you know how to use Flutter Shared Preferences Plugin.

  1. Install Shared_Preferences Plugin from Flutter Packages Website.

    1
    2
    dependencies:
    shared_preferences: ^0.5.3+4
  2. Import the Shared Preferences Plugin

    1
    import 'package:shared_preferences/shared_preferences.dart';
  3. We are going to use TextField widget and Switch widget. So, we need to declare the variables for those widgets.
    TextField widget needs TextEditingController, and Switch widget needs bool variables. Declare those variables in State class.

    1
    2
    TextEditingController _controller = TextEditingController(text: "LOVE");
    bool isON = false;
  4. we need to use the variables in the widget

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    ListView(
    children: <Widget>[
    ListTile(
    title: TextField(
    controller: _controller,
    ),
    ),
    Container(
    child: Switch(
    value: isON,
    onChanged: (newValue) {
    setState((){
    isON = newValue;
    });
    },
    ),
    ),
    ],
    ),
  5. We need setter and getter method.

  • Setter Method

    1
    2
    3
    4
    5
    Future<void> _setStringSharedPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString("inputText", _controller.text);
    prefs.setBool("isON", isON);
    }
  • Getter Method

    1
    2
    3
    4
    5
    6
    7
    8
    9
    Future<String> _getStringFromSharedPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString("inputText") ?? "LOVE";
    }

    Future<bool> _getBoolFromSharedPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool("isON") ?? false;
    }
  1. In order to save the data when the TextField and Switch is changed, add Setter Method to isChanged property.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    TextField(
    controller: _controller,
    onChanged: (text) {
    _setStringSharedPref();
    },
    ),

    Switch(
    value: isON,
    onChanged: (newValue) {
    setState(() {
    isON = newValue;
    });
    _setStringSharedPref();
    },
    ),
  2. Add initState() and add Getter Method to get the Shared Prefereces values when launching the application.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @override
    void initState() {
    super.initState();
    _getStringFromSharedPref().then((s) {
    _controller.text = s;
    });
    _getBoolFromSharedPref().then((b) {
    isON = b;
    });
    }
Share