Flutter Tutorial:
Flutter Widgets:
Flutter Advance
Flutter REST API
Advanced Concepts
Wrap vs Builder vs OverBarFlow
Circular progress contain Icon
Flutter State management Comparison
Flutter Database
Flutter Token Expired Handling
Flutter Provider
Flutter GetX
Flutter with Native
Flutter Tips:
Interview Questions
Flutter 100 Interview Questions
Implement Shared Preferences in Flutter
Step 1:–
Run this command in the terminal
flutter pub add shared_preferences
OR
shared_preferences: #use latest version and add in pubspec.yaml file
Step 2:-
store String form data in SharedPreferences
storeDataInSharedPref(data) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Note here we use key1 as a unique key which store data in sharedPreferences
await prefs.setString('key1', data); //
}
Step 3:-
Fetch String form of data based on the Unique Key
Note: always use unique key to store data example access_token , user_password, credit_card_number etc
Future<String?>? fetchSharedPrefData(key) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Note here we use pass key
var value = await prefs.getString(key); //
// print("value >>>>> $value");
return value;
}
Step 4:-
Now in this container we use Shared Preferences where user can store and fetch data through elevated button
Note: here we are using setState(), according to your state management you can use other options which refresh the variable or widget information
Container(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
TextFormField(
controller: controller,
decoration: InputDecoration(
hintText: 'Store data',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
const SizedBox(
height: 5,
),
const SizedBox(
height: 10,
),
ElevatedButton(
child: const Text(
"Save in SharedPref",
),
onPressed: () async {
if (controller.text != null) {
//Here we store Shared Preferences storeDataInSharedPref(controller.text);
}
},
),
const SizedBox(
height: 15,
),
ElevatedButton(
onPressed: () async {
//Here we fetch Shared Preferences fetchSharedPrefData('key1')?.then((value) {
setState(() {
newValue = value.toString();
});
});
// print("newValue $newValue");
},
child: const Text('Show Stored daata')),
SizedBox(
height: 5,
),
Text(newValue.toString())
],
),
)
Full Code of implement Sharedpreferences in Flutter
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ResearchThinker',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MySharedPrefExample(),
);
}
}
class MySharedPrefExample extends StatefulWidget {
const MySharedPrefExample({Key? key}) : super(key: key);
@override
State<MySharedPrefExample> createState() => _MySharedPrefExampleState();
}
class _MySharedPrefExampleState extends State<MySharedPrefExample> {
TextEditingController controller = TextEditingController();
var newValue = '';
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('ResearchThinker Flutter Examples'),
),
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
TextFormField(
controller: controller,
decoration: InputDecoration(
hintText: 'Store data',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
const SizedBox(
height: 5,
),
const SizedBox(
height: 10,
),
ElevatedButton(
child: const Text(
"Save in SharedPref",
),
onPressed: () async {
if (controller.text != null) {
//Here we store Shared Preferences storeDataInSharedPref(controller.text);
}
},
),
const SizedBox(
height: 15,
),
ElevatedButton(
onPressed: () async {
//Here we fetch Shared Preferences fetchSharedPrefData('key1')?.then((value) {
setState(() {
newValue = value.toString();
});
});
// print("newValue $newValue");
},
child: const Text('Show Stored daata')),
SizedBox(
height: 5,
),
Text(newValue.toString())
],
),
),
),
),
);
}
//Below functions used for Storing and fetching shared preferences
storeDataInSharedPref(data) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Note here we use key1 as a unique key which store data in sharedPreferences
await prefs.setString('key1', data); //
}
Future<String?>? fetchSharedPrefData(key) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Note here we use pass key
var value = await prefs.getString(key); //
// print("value $value");
return value;
}
}
If you have any query, please comment below, we will reply soon