Using Local Storage in Flutter

Santhosh Adiga U
4 min readFeb 28, 2023

--

Local storage is a very important feature for mobile apps, allowing data to be stored locally on a user’s device instead of constantly having to retrieve it from a remote server. In Flutter, local storage can be implemented using the shared_preferences package. In this blog post, we’ll cover how to use this package to store and retrieve data locally.

Setting up shared_preferences Package

First, you need to add the shared_preferences package to your project. To do this, open the pubspec.yaml file and add the following line under dependencies:

dependencies: 
flutter: sdk:
flutter shared_preferences: ^2.0.6

Then run flutter pub get to download and install the package.

Storing Data Locally

To store data locally, you will need to create an instance of the SharedPreferences class. You can do this by calling the getInstance() method:

SharedPreferences prefs = await SharedPreferences.getInstance();

Once you have an instance of SharedPreferences, you can use it to store data using the set method. The set method takes two parameters: a key and a value. The key is a string that identifies the data you are storing, and the value can be any primitive data type (such as int, bool, double, or String). Here's an example:

prefs.setInt('counter', 42);

In this example, we’re storing an integer value of 42 with the key ‘counter’. This value can be retrieved later using the same key.

Retrieving Data from Local Storage

To retrieve data from local storage, you can use the get method. This method takes one parameter, the key of the data you want to retrieve:

int counter = prefs.getInt('counter') ?? 0;

In this example, we’re retrieving the value of the ‘counter’ key that we stored earlier. We’re also using the ?? operator to provide a default value of 0 if the 'counter' key doesn't exist in local storage.

Updating Data in Local Storage

To update data in local storage, you can simply call the set method again with the same key:

prefs.setInt('counter', counter + 1);

In this example, we’re incrementing the value of the ‘counter’ key by 1 and storing the updated value in local storage.

Deleting Data from Local Storage

To delete data from local storage, you can use the remove method. This method takes one parameter, the key of the data you want to remove:

prefs.remove('counter');

In this example, we’re removing the value of the ‘counter’ key from local storage.

Complete Example

Here’s a complete example that demonstrates how to use SharedPreferences to store, retrieve, update, and delete data locally:

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

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

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
int _counter = 0;

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

void _loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counter = prefs.getInt('counter') ?? 0;
});
}

void _incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0) + 1;
prefs.setInt('counter', _counter);
});
}

void _resetCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counter = 0;
prefs.remove('counter');
});
}

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Local Storage Demo',
home: Scaffold(
appBar: AppBar(
title: Text('Local Storage Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Counter:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
SizedBox(width: 16),
ElevatedButton(
onPressed: _resetCounter,
child: Text('Reset'),
),
],
),
],
),
),
),
);
}
}

In this example, we have a simple app that displays a counter and two buttons to increment and reset the counter. We’re using SharedPreferences to store the value of the counter locally, so that it persists even when the app is closed. In the initState method, we’re calling loadCounter to retrieve the value of the counter from local storage. We’re using setState to update the state of the app and display the value of the counter. In the _increamentCounter method, we’re retrieving the value of the counter from local storage, incrementing it by 1, and storing the updated value back in local storage using the _setInt method. In the _resetCounter method, we’re resetting the value of the counter to 0 and removing the counter key from local storage using the remove method. In the build method, we’re displaying the value of the counter and two buttons to increment and reset it. We’re using setState to update the state of the app when the counter is incremented or reset.

Conclusion :

In this blog post, we’ve covered how to use the SharedPreferences package in Flutter to store and retrieve data locally. We’ve seen how to set up the package, store data using the set method, retrieve data using the get method, update data using the set method again, and delete data using the remove method. We’ve also provided a complete example that demonstrates how to use SharedPreferences to build a simple app that persists data locally. We hope this blog post has been helpful in understanding how to use local storage in Flutter.

--

--

Santhosh Adiga U
Santhosh Adiga U

Written by Santhosh Adiga U

Founder of Anakramy ., dedicated to creating innovative AI-driven cybersecurity solutions.

No responses yet