HomeMobile DevelopmentFlutter local storage - shared preferences free source code Flutter local storage - shared preferences free source code Makarablue October 20, 2022 0 Video: Code: import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; final Future _prefs = SharedPreferences.getInstance(); void main() { runApp(const MaterialApp( debugShowCheckedModeBanner: false, home: SaveLocalDemo())); } class SaveLocalDemo extends StatefulWidget { const SaveLocalDemo({Key? key}) : super(key: key); @override State createState() => _SaveLocalDemoState(); } class _SaveLocalDemoState extends State { TextEditingController myText = TextEditingController(); String getData = ""; @override void initState() { // TODO: implement initState super.initState(); getText(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color.fromARGB(255, 253, 247, 237), body: SizedBox( width: MediaQuery.of(context).size.width * 0.9, height: MediaQuery.of(context).size.height * 0.3, child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [myForm(), myDispay()], ), ), ); } Widget myForm() { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( width: MediaQuery.of(context).size.width * 0.7, child: TextFormField( controller: myText, )), IconButton(onPressed: () => save(), icon: const Icon(Icons.save)) ], ); } Widget myDispay() { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "Saved data will display below\n", style: TextStyle(color: Colors.blue, fontSize: 14), ), Text(getData) ], ); } save() async { final SharedPreferences prefs = await _prefs as SharedPreferences; if (myText.value.text.isNotEmpty) { prefs.setString("myKey", myText.value.text); } } getText() async { final SharedPreferences prefs = await _prefs as SharedPreferences; setState(() { getData = prefs.getString('myKey').toString(); }); } } Tags Android App Coding Flutter Mobile Development Newer Older