Shared Preferences Simple
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});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Hello Flutter ",
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.brown,
),
home: const FlutterShared(),
);
}
}
class FlutterShared extends StatefulWidget {
const FlutterShared({super.key});
@override
State<FlutterShared> createState() {
return SharedState();
}
}
class SharedState extends State<FlutterShared> {
var nameController = TextEditingController();
//static const String KEYNAME = "name";
var nameValue = "No Value Saved";
//initState() function can never handle asynchronously.we can never write "async" to initState() function
@override
void initState() {
super.initState();
getValue();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusManager.instance.primaryFocus?.unfocus();
},
child: Scaffold(
drawer: const Drawer(),
appBar: AppBar(
title: const Text(
"Flutter Shared preferences",
style: TextStyle(fontWeight: FontWeight.bold),
),
centerTitle: true,
backgroundColor: Colors.grey,
),
body: Container(
child: Center(
child: SizedBox(
width: 200,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
controller: nameController,
decoration: InputDecoration(
hintText: "Enter Name...",
label: const Text("Name"),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(
width: 2,
),
),
),
),
const SizedBox(
height: 40,
),
ElevatedButton(
onPressed: () async {
print("1"); //for checking execution
var name = nameController.text.toString();
var prefs = await SharedPreferences.getInstance();
///Any task which return in "Future" class then that task should be handled asynchronously
/// so that UI part will not be on hold Any function or class which take indefinite time to execute
/// then that function/class will be handled through "await" and will make asynchronous
prefs.setString("name", name);
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
fixedSize: const Size(350.0, 50.0),
),
child: const Text(
"Save",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 20.0),
),
),
const SizedBox(
height: 40,
),
Text(nameValue),
],
),
),
),
),
),
);
}
void getValue() async {
var prefs = await SharedPreferences.getInstance();
var getName = prefs.getString("name");
nameValue = getName != null ? getName : "No Value Saved";
///nameValue = getName ?? "No Value Saved";
setState(() {});
}
}
Comments
Post a Comment