Starting with Flutter: Working with SharedPreferences & UserDefaults

There could be a time where you need to just save a simple value, like a boolean, a string or even an integer. This very easy task can result in useless complications if you save it into a file or into a database. Small & easy tasks should let you use easy and quick solutions. Let’s introduce shared_preferences then!

Android and iOS have different ways to perma-save small data, Android has SharedPreferences class, which represents an app-managed XML file (ore more files) with key-value elements, also they can be shared across other applications. UserDefaults is iOS way to store simple data, representing a simple synchronous database with cache features.

Flutter doesen’t have a built-in way to access these interfaces but a plugin directly created by Flutter Developers comes on our aid: shared_preferences. This simple plugin will let you use SharedPreferences and UserDefaults without worrying about the platform your app is running on! Let’s see a simple example to know better how to use it!

Here we have a simple app with a textbox, 2 buttons and a text. We want to save the input witha button and show it with the other button.

final textController = TextEditingController();

@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.red,
          title: Text('Some Awesome Flutter App'),
        ),
        body: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(
                width: 300,
                child: TextField(
                  controller: textController,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.black, width: 1.0),
                    ),
                    hintText: 'Enter some data'
                  ),
                ),
              ),
              RaisedButton(
                child: Text('Save', style: TextStyle(color: Colors.white)),
                onPressed: null
              ),
              RaisedButton(
                child: Text('Show', style: TextStyle(color: Colors.white)),
                onPressed: null
              ),
              Text(
                ''
              )
            ],
          )
        )
    );
  }

Let’s give our ‘Save’ button some action by populating its onPressed method:

RaisedButton(
     child: Text('Save', style: TextStyle(color: Colors.white)),
     onPressed: () => saveText()
),


void saveText(){
    String text = textController.text;
    //Here we'll save our text
  }

Our saveText method can be now populated with shared_preferences methods.

First thing first, we need to istantiate our class, then just wait that it writes our data with an async method: setString. SharedPreference object have different methods for different type of data: setIntsetBool… even setStringList. We also wish to print if the data is saved correctly, any “set” method return a Future<bool> so we know if everything goes well. Let’s give our text as key “OurText”.
Our code will become:

RaisedButton(
     child: Text('Save', style: TextStyle(color: Colors.white)),
     onPressed:() async {
          print(await saveText());
     },
),

Future<bool> saveText() async{
    String text = textController.text;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString('OurText', text);
  }

Writing something on our TextField, then clicking “save” will result then in:

[+12369 ms] I/flutter ( 9987): true

Now we should show our text. Time to work on ‘Show’ button:

Like saving we instantiate SharedPreferences then get our string with… getString (applause…). SharedPreferences.getInstance() is a future so we’ll need to get our String in a async method:

String ourText = '';

RaisedButton(
      child: Text('Show', style: TextStyle(color: Colors.black)),
      onPressed: () async {
          ourText = await getText();
          setState(() {
          });
      },
),
Text(
   ourText
)

Future<String> getText() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString('OurText');
  }

And there we have:

Our text now is saved on SharedPreferences and UserDefaults, so even if we kill the app we can still show it without writing it down.

Add a Comment

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