Saving and reading data in Flutter with SharedPreferences

Sajid Ahmed
2 min readJan 30, 2020

In Flutter, Shared Preferences are used to store primitive data (int, double, bool, string, and stringList). This data is associated with the app, so when the user uninstalls your app, the data will also be deleted. It is meant for storing small amounts of data.

Get the plugin :

dependencies:
flutter:
sdk: flutter
shared_preferences: ^0.5.6

Import the package

import ‘package:shared_preferences/shared_preferences.dart’;

Reading and writing data

To get the shared preferences object you can do the following:

final prefs = await SharedPreferences.getInstance();

This will be used for all of the following examples.

int

// read
final myInt = prefs.getInt(‘my_int_key’) ?? 0;

// write
prefs.setInt(‘my_int_key’, 42);

double

// read
final myDouble = prefs.getDouble(‘my_double_key’) ?? 0.0;

// write
prefs.setBool(‘my_bool_key’, true);

bool

// read
final myBool = prefs.getBool(‘my_bool_key’) ?? false;

// write
prefs.setBool(‘my_bool_key’, true);

string

// read
final myString = prefs.getString(‘my_string_key’) ?? ‘ ’;

// write
prefs.setString(‘my_string_key’, ‘hello’);

stringList

// read
final myStringList = prefs.getStringList(‘my_string_list_key’)??[];

// write
prefs.setStringList(‘my_string_list_key’, [‘horse’, ‘cow’, ‘sheep’]);

Remove data

To delete data, use the remove() method.

final prefs = await SharedPreferences.getInstance();prefs.remove('counter');

Limitation

There is a limitations of SharedPreference data. In my case it throw a Memory Exception when SharedPreference data cross 1428.51-kb.

So its better to use SQLite database when you required huge data to store.

--

--