Pandiyan Mani
3 min readNov 15, 2022

Shared Preference in Flutter

So first start with the dependencies that needed for share preference by adding it in pubspec.yaml

dependencies:
flutter:
sdk: flutter


# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
sqflite: ^2.0.6

Next I am going to create an LoginPage.dart file which holds two data one is username and user email.so I am creating a TextFormField for this two fields

child: Column(
children: [
TextFormField(
controller: _username,
validator: (value) {
if (value == null || value.isEmpty) {
return "Username field is empty";
}
return null;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
labelText: "Enter Username")
),
SizedBox(height: 20,),
TextFormField(
controller: _useremail,
validator: (value) {
if (value == null || value.isEmpty) {
return "Email ID is empty";
}
return null;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
labelText: "Enter Email ID")
),
SizedBox(height: 20,),
ElevatedButton(onPressed: () {
if(_formkey.currentState!.validate()) {

}
},
child: Text("SAVE"))
],
)

In above you can see two input fields for getting name and email id with button for saving .On press of save button I am doing validation. So next once the validation success i am going to save the data in the local storage

Method for saving Details

Future<void> saveData(String name, String emailId) async {
SharedPreferences sp = await SharedPreferences.getInstance();
setState(() {
sp.setString("name", name);
sp.setString("emailid", emailId);
});
}

Getting Saved Data

Future _getDetails() async {
SharedPreferences sp = await SharedPreferences.getInstance();
setState(() {
_getSavedName = sp.getString("name") ?? "";
_getSavedEmail = sp.getString("emailid") ?? "";
});
}

Lets see the entire code for LoginPage.dart

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

class LoginPage extends StatefulWidget {
const LoginPage({Key? key}) : super(key: key);

@override
State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
final _formkey = GlobalKey<FormState>();
TextEditingController _username = TextEditingController();
TextEditingController _useremail = TextEditingController();

String _getSavedName = "";
String _getSavedEmail = "";

Future<void> saveData(String name, String emailId) async {
SharedPreferences sp = await SharedPreferences.getInstance();
setState(() {
sp.setString("name", name);
sp.setString("emailid", emailId);
});
}

Future _getDetails() async {
SharedPreferences sp = await SharedPreferences.getInstance();
setState(() {
_getSavedName = sp.getString("name") ?? "";
_getSavedEmail = sp.getString("emailid") ?? "";
print(_getSavedName);
print(_getSavedEmail);
});
}


@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Form(
key: _formkey,
child: Padding(
padding: EdgeInsets.all(10),
child: Column(
children: [
TextFormField(
controller: _username,
validator: (value) {
if (value == null || value.isEmpty) {
return "Username field is empty";
}
return null;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
labelText: "Enter Username")
),
SizedBox(height: 20,),
TextFormField(
controller: _useremail,
validator: (value) {
if (value == null || value.isEmpty) {
return "Email ID is empty";
}
return null;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
labelText: "Enter Email ID")
),
SizedBox(height: 20,),
ElevatedButton(onPressed: () {
if(_formkey.currentState!.validate()) {
saveData(_username.text, _useremail.text);
}
},
child: Text("SAVE")),
SizedBox(height: 10,),
ElevatedButton(onPressed: () {
_getDetails();
},
child: Text("FETCH"))
],
),
),
),
),
);
}
}

We have to call this from main.dart

import 'package:flutter/material.dart';

import 'LoginPage.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: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const LoginPage(),
);
}
}

Screen Shot of final output. You can see the data once you saved by clicking fetch button and it will print on the console

No responses yet