Flutter provides us the opportunity to create beautiful mobile applications If we want to invoke any functionality of the device we need to add a plugin of it. We will learn by adding Shared Preferences plugin in our application.
Create an application and name it "shared_preferences_demo" then add the following code in its lib/main.dart file
import 'package:flutter/material.dart';
void main() => runApp(SharedPreferencesDemo());
class SharedPreferencesDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Shared Preferences Demo',
home: HomePage(title: 'Shared Preferences Demo'),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
TextEditingController textController = new TextEditingController();
String savedData = "";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: <Widget>[
TextField(
controller: textController,
),
FlatButton(
child: Text("Save In Shared Preferences"),
onPressed: () {
saveInSharedPreferences();
},
color: Colors.redAccent,
),
Padding(
padding: EdgeInsets.all(10),
),
Text(savedData),
FlatButton(
child: Text("Get from Shared Preferences"),
onPressed: () {
getFromSharedPreferences();
},
color: Colors.greenAccent,
),
],
));
}
void saveInSharedPreferences() {
debugPrint('save pressed');
}
void getFromSharedPreferences() {
debugPrint('get pressed');
}
}
Finding a plugin:
1. There are various flutter plugins available on the https://pub.dartlang.org/flutter, One can search and find a plugin there easily.
2. Search for shared preferences.
3. Select shared_preferences option.
4. Open Installing tab - Here you will learn how to integrate this plugin in your application.
Integrating Plugin in Our Application
1. Open pubspec.yaml file of your project
2. Add the following in your dependencies.
dependencies:
shared_preferences:
3. Install it via command
flutter packages get
4. Import in your code as the following
import 'package:shared_preferences/shared_preferences.dart';
Add the following code in your lib/main.dart file.
1. Add this in saveInSharedPreferences method
void saveInSharedPreferences() async {
String dataToSave = textController.text;
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('data', dataToSave);
textController.text = '';
}
2. Add this in getFromSharedPreferences method
void getFromSharedPreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
savedData = await prefs.getString('data');
debugPrint(savedData);
}
Run the app.
Now you will be able to save and get from shared preferences in your application.
Hope you enjoyed my post
References:
1. https://pub.dartlang.org/
2. https://github.com/flutter/plugins