Flutter SharedPreferences

Flutter SharedPreferences:

In Android we used key-value pairs to store small collection of data by using SharedPreferences API.

But In Flutter,  this functionality can be performed by using the Shared_Preferences plugin. This plugin In Flutter wraps the functionality of both Shared Preferences for Android  and NSUserDefaults for IOS.

  • This plugin is used to store persistent simple data. irrespective of the platform means for both Android and IOS. This plugin is not used for storing critical data. Data is persisted to disk asynchronously. It’s not designed to store a lot of data.

Adding Flutter SharedPreferences Dependencies :

To use SharedPreferences in Flutter App we have to add its dependencies in ” pubspec.yaml file. ”

Below is the example shows adding SharedPreferences dependenices.

dependencies:
flutter:
sdk: flutter
shared_preferences: "<newest version>"

Use the below code in example.

pubspec.yaml file
dependencies:
shared_preferences: ^0.4.3

We can add this SharedPreferences dependencies in three ways based on the your development Platforms

  • AndroidStudio:

For  Android Studio/IntelliJ: Click ‘Packages Get’ in the action ribbon at the top of pubspec.yaml

  • VSCode

For VS Code: Click ‘Get Packages’ located in right side of the action ribbon at the top of pubspec.yaml

  • Terminal Editor:

for terminal: Run this code from terminal console  flutter packages get.

After adding the dependencies we are importing the SharedPreferences Package inside the Dartcode and here we are using SharedPrefeences. Without adding dependencies if we use Sharedpreferences then it shows Package not found Error.

Using below code we are importing the SharedPreferences In Flutter DartCode for coding.

import 'package:shared_preferences/shared_preferences.dart';

The below example code describes using the SharedPreferences:

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

void main() {
runApp(new MaterialApp(
home: new Scaffold(
body: new Center(
child: new RaisedButton(
onPressed: _incrementCounter,
child: new Text('Increment Counter'),
),

),
),
));
}

_incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int counter = (prefs.getInt('counter') ?? 0) + 1;
print('Pressed $counter times.');
await prefs.setInt('counter', counter);
}

You can get the data into your app with SharedPreferences by running below code:

const MethodChannel('plugins.flutter.io/shared_preferences')
.setMockMethodCallHandler((MethodCall methodCall) async {
if (methodCall.method == 'getAll') {
return <String, dynamic>{}; // set initial values here if desired
}
return null;
});

example/lib/main.dart

//

// Here we are importing SharedPreferences Package

//
import 'dart:async';

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: 'SharedPreferences Demo',
home: SharedPreferencesDemo(),
);
}
}

// Here we are creating SharedPreferences class that extends StatefulWidget
class SharedPreferencesDemo extends StatefulWidget {
SharedPreferencesDemo({Key key}) : super(key: key);

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

class SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<int> _counter;

Future<Null> _incrementCounter() async {
final SharedPreferences prefs = await _prefs;
final int counter = (prefs.getInt('counter') ?? 0) + 1;

setState(() {
_counter = prefs.setInt("counter", counter).then((bool success) {
return counter;
});
});
}

@override
void initState() {
super.initState();
_counter = _prefs.then((SharedPreferences prefs) {
return (prefs.getInt('counter') ?? 0);
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("SharedPreferences Demo"),
),

body: Center(
child: FutureBuilder<int>(
future: _counter,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const CircularProgressIndicator();
default:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');

else
return Text(
'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n'
'This should persist across restarts.',
);
}
})),

floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}

 

Save data:

To save the   persist data, we can use the setter methods provided by the SharedPreferences class. Setter methods are available in different data  types, such as setInt, setBool, and setString.

Setter methods can do two things: First, synchronously it update the key-value pair in-memory. Then, persist the data to disk.

// obtain shared preferences
final prefs = await SharedPreferences.getInstance();

// set value
prefs.setInt('counter', counter);

 

Read data:

To read data, we can use getter method provided by the SharedPreferences class. For each setter there is a corresponding getter method. For example, getter method supports different data types we can use them as follows   getInt, getBool, and getString methods.

final prefs = await SharedPreferences.getInstance();

// Try reading data from the counter key. If it does not exist, return 0.
final counter = prefs.getInt('counter') ?? 0;

Remove data:

To delete persist data, we can use the remove method. it will deletes the data. use the below code to delete data.

final prefs = await SharedPreferences.getInstance();

prefs.remove('counter');

Testing support:

We can test code that persists data using shared_preferences. To do so, we’ll need to mock out the MethodChannel used by the shared_preferences library.

We can get  SharedPreferences with initial values in our tests by running the following code in a setupAll method in our test files:

const MethodChannel('plugins.flutter.io/shared_preferences')
.setMockMethodCallHandler((MethodCall methodCall) async {
if (methodCall.method == 'getAll') {
return <String, dynamic>{}; // set initial values here if desired
}
return null;
});

 

Complete SharedPreferences  Example given below:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
// This widget is the root of our application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Shared preferences demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Shared preferences demo'),
);
}

}

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

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

class _MyHomePageState extends State<MyHomePage> {
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(
'You have pushed the button this many times:',
),

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.
);
}
}

 Congratulations You Have Learned  Flutter SharedPreferences and Using In Flutter.

1 Response

Leave a Reply

Categories