7 Ways to Use Shared Preferences in Flutter

7 Ways to Use Shared Preferences in Flutter

Shared Preferences in Flutter – Key-value data is commonly stored Shared Preferences in Flutter. This article will examine Flutter Shared Preferences and how it stores and retrieves data.

What is Shared Preferences in Flutter?

Shared Preferences stores small amounts of data in a lightweight key-value store. Shared Preferences in Flutter is a simple and convenient way to store and retrieve user preferences or other small amounts of data. The Android SDK SharedPreferences library powers Shared Preferences.

The best way to implement Shared Preferences in Flutter.

Implementation of Shared Preferences in Flutter is very straightforward. Our Flutter project won’t be complete until the Shared Preferences package is integrated. The following line can be added to our pubspec.yaml file:

dependencies:
  shared_preferences: ^2.1.0

We can store and retrieve data with the package after adding it to our project. A user’s name can be stored and retrieved using Shared Preferences in Flutter:

import 'package:shared_preferences/shared_preferences.dart';

// Store user's name
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('name', 'John Doe');

// Retrieve user's name
String name = prefs.getString('name');

First, we get a new instance of Shared Preferences in Flutter by invoking its getInstance() function in the preceding example. To save the user name under the key name, we call setString(). When everything else fails, we can always go to the Shared Preferences store and the getString() method to retrieve the user name.

Shared Preferences in Flutter can include:

In addition to texts, integers, booleans, and doubles, Shared Preferences in Flutter can also store boolean values. Data types allowed are as follows:

  • bool
  • double
  • int
  • String

Shared preferences using Boolean:

The usage of Booleans, a very simple data type, is widespread in the creation of mobile applications. The setBool() and getBool() methods of Shared Preferences are used to save and retrieve boolean values, respectively. So, to example:

// Store a boolean value
await prefs.setBool('dark_mode', true);

// Retrieve a boolean value
bool _darkMode = prefs.getBool('dark_mode');
Shared Preferences in Flutter

The previous example stores a boolean value under the key is_logged_in using setBool(). We then receive the boolean value and save it in the isLoggedIn variable using getBool().

Shared preferences using Integer:

Mobile app developers also employ integers. SetInt() and getInt() can store and retrieve integer values in Shared Preferences. An example:

// Store an integer value
await prefs.setInt('user_id', 1234);

// Retrieve an integer value
int userId = prefs.getInt('user_id');
Shared Preferences in Flutter

The above example stores an integer value under the key user_id using setInt(). We then use getInt() to acquire the integer value and store it in userId.

Shared preferences using Double:

Doubles represent floating-point numbers. SetDouble() and getDouble() can save and retrieve double values in Shared Preferences in Flutter. An example:

// Store a double value
await prefs.setDouble('latitude', 37.7749);

// Retrieve a double value
double latitude = prefs.getDouble('latitude');
Shared Preferences in Flutter

The above example stores a double value under the key latitude using setDouble(). We then extract the double value using getDouble() and store it in latitude.

Shared preferences using String:

Mobile app development uses strings. SetString() and getString() can store and retrieve string values in Shared Preferences. An example:

// Store a string value
await prefs.setString('user_email', '[email protected]');

// Retrieve a string value
String userEmail = prefs.getString('user_email');
Shared Preferences in Flutter

The above example stores a string value beneath the key user_email using setString(). We then extract the string value using getString() and store it in userEmail.

Shared preferences using List:

Shared Preferences stores data lists. Flutter json.encode() and json.decode() methods convert lists to JSON-encoded strings and back again. An example:

import 'dart:convert';

// Store a list of strings
List<String> interests = ['Flutter', 'Dart', 'Mobile App Development'];
String encodedInterests = json.encode(interests);
await prefs.setString('interests', encodedInterests);

// Retrieve a list of strings
String encodedInterests = prefs.getString('interests');
List<String> interests = json.decode(encodedInterests);
Shared Preferences in Flutter

First, we define an interests string list. We then encode the interests list using json.encode(). Shared Preferences stores the JSON-encoded string under key interests. To get the list from Shared Preferences, we decode the JSON string with json.decode().

Complete code

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Shared Preferences in Flutter',
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _darkMode = false;
  int _counter = 0;
  double _latitude = 0.0;
  String _userEmail = '';
  List<String> _interests = [];

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _loadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _darkMode = prefs.getBool('dark_mode') ?? false;
      _counter = prefs.getInt('counter') ?? 0;
      _latitude = prefs.getDouble('latitude') ?? 0.0;
      _userEmail = prefs.getString('user_email') ?? '';
      String encodedInterests = prefs.getString('interests') ?? '[]';
      _interests = List<String>.from(json.decode(encodedInterests));
    });
  }

  Future<void> _toggleDarkMode() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _darkMode = !_darkMode;
      prefs.setBool('dark_mode', _darkMode);
    });
  }

  Future<void> _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter++;
      prefs.setInt('counter', _counter);
    });
  }

  Future<void> _setLatitude(double value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _latitude = value;
      prefs.setDouble('latitude', value);
    });
  }

  Future<void> _setUserEmail(String value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _userEmail = value;
      prefs.setString('user_email', value);
    });
  }

  Future<void> _setInterests(List<String> value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String encodedInterests = json.encode(value);
    setState(() {
      _interests = value;
      prefs.setString('interests', encodedInterests);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(children: [
          Image.asset(
            'assets/logo.png',
            height: 30,
          ),
          Text('flutterflux.com')
        ]),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SwitchListTile(
              title: Text('Dark Mode'),
              value: _darkMode,
              onChanged: (bool value) {
                _toggleDarkMode();
              },
            ),
            SizedBox(height: 16.0),
            Text(
              'Counter: $_counter',
              style: TextStyle(fontSize: 24.0),
            ),
            SizedBox(height: 16.0),
            ElevatedButton(
              child: Text('Increment Counter'),
              onPressed: () {
                _incrementCounter();
              },
            ),
            SizedBox(height: 16.0),
            Text(
              'Latitude: $_latitude',
              style: TextStyle(fontSize: 24.0),
            ),
            SizedBox(height: 16.0),
            Slider(
              value: _latitude,
              min: -90.0,
              max: 90.0,
              onChanged: (double value) {
                _setLatitude(value);
              },
            ),
            SizedBox(height: 16.0),
            TextFormField(
              decoration: InputDecoration(
                labelText: 'Email',
                hintText: 'Enter your email',
              ),
              initialValue: _userEmail,
              onChanged: (String value) {
                _setUserEmail(value);
              },
            ),
            SizedBox(height: 16.0),
            Wrap(
              spacing: 8.0,
              children: <Widget>[
                FilterChip(
                  label: Text('Sports'),
                  selected: _interests.contains('Sports'),
                  onSelected: (bool value) {
                    if (value) {
                      _interests.add('Sports');
                    } else {
                      _interests.remove('Sports');
                    }
                    _setInterests(_interests);
                  },
                ),
                FilterChip(
                  label: Text('Music'),
                  selected: _interests.contains('Music'),
                  onSelected: (bool value) {
                    if (value) {
                      _interests.add('Music');
                    } else {
                      _interests.remove('Music');
                    }
                    _setInterests(_interests);
                  },
                ),
                FilterChip(
                  label: Text('Movies'),
                  selected: _interests.contains('Movies'),
                  onSelected: (bool value) {
                    if (value) {
                      _interests.add('Movies');
                    } else {
                      _interests.remove('Movies');
                    }
                    _setInterests(_interests);
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
7 Ways to Use Shared Preferences in Flutter

In this example, a MyHomePage widget shows SharedPreferences usage cases. We have five data variables:

1. _darkMode – dark mode state as a boolean.

2. _counter – an integer value to store the counter.

3. _latitude – a double value to store the latitude.

4. _userEmail – a string value to store the user’s email.

5. _interests – a list of strings to store the user’s interests.

We also developed SharedPreferences routines to load, store, and update data. These tasks:

1. _loadData() – a function to load all the data from `SharedPreferences`.

2. _toggleDarkMode() – a function to toggle the `darkMode` variable and save it to SharedPreferences.

3. _incrementCounter() – a function to increment the counter variable and save it to SharedPreferences.

4. _setLatitude(double value) – a function to set the latitude variable and save it to SharedPreferences.

5. _setUserEmail(String value) – a function to set the userEmail variable and save it to SharedPreferences.

6. _setInterests(List<String> value) – a function to set the interests variable and save it to SharedPreferences.

In the build() method, we have used various Flutter widgets to display the data and to allow the user to interact with it. We have used:

1. SwitchListTile – a widget to display and toggle the dark mode.

2. Text – a widget to display the counter and the latitude.

3. ElevatedButton – a widget to increment the counter.

4. Slider – a widget to set the latitude.

5. TextFormField – a widget to set the user email.

6. Wrap and FilterChip – widgets to set the user’s interests.

We have also called the _loadData() function in the initState() method to load the data from SharedPreferences when the widget is initialized.

Conclusion

Shared Preferences in Flutter, a powerful Flutter package, lets developers store and retrieve modest quantities of data rapidly. We covered boolean, integer, double, string, and list in Shared Preferences in this post. We also examined how to store and retrieve data using Shared Preferences and how to store and retrieve lists using json.encode() and json.decode(). With this article information, developers can use Shared Preferences to design better mobile apps for users. read too Mastering ModalBottomSheet in Flutter: A Comprehensive Guide

Hello, I'm Cakra. I'm currently occupied with developing an application using the Flutter framework. Additionally, I'm also working on writing some articles related to it.

You May Also Like