Flutter – Saving Data in Local using Shared Preferences

By | October 4, 2018

This simple example demonstrates saving an integer value in the local shared preferences.
We will use a flutter plugin called shared_preferences for this.
You can read more about the plugin from here.

Add Dependency

First thing is to add the package to the dependencies.
Go to pubspec.yaml and add the package.

[java]
dependencies:
flutter:
sdk: flutter
shared_preferences: "0.4.3"
[/java]

Example

[java]
import ‘package:flutter/material.dart’;
import ‘package:shared_preferences/shared_preferences.dart’;

class PreferenceDemo extends StatefulWidget {
PreferenceDemo({Key key, this.title}) : super(key: key);
final String title;

@override
_PreferenceDemo createState() => _PreferenceDemo();
}

class _PreferenceDemo extends State<PreferenceDemo> {
int _counter = 0;

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

//Loading counter value on start
_loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt(‘counter’) ?? 0);
});
}

//Incrementing counter after click
_incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt(‘counter’) ?? 0) + 1;
prefs.setInt(‘counter’, _counter);
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
‘Saved counter in Preferences and Reloaded…’,
),
Text(
‘$_counter’,
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: ‘Increment’,
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
[/java]

Leave a Reply

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