Home > Enterprise >  How to save data locally using shared preferences
How to save data locally using shared preferences

Time:12-02

i want save data locally in device, when i will terminate my app and when i will reopen i want my previous data to be stored locally.so how i can save that using shared preferences in flutter

here my home page where i set value:

import 'package:flutter/material.dart';
import 'package:list_ex/product.dart';
import 'package:sizer/sizer.dart';
import 'package:list_ex/info.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'shared_pref.dart';


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


  @override
  State<Myhome> createState() => _MyhomeState();
}

class _MyhomeState extends State<Myhome> {
  List <Data> productdata = [];
  final myController = TextEditingController();
  TextEditingController productController = TextEditingController();
  TextEditingController prizeController = TextEditingController();
  late SharedPreferences sharedPreferences;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getprodata();
    getpridata();


    @override
    void dispose() {
      // Clean up the controller when the widget is disposed.
      myController.dispose();
      super.dispose();
    }
  }
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Products',
            style: TextStyle(
              fontSize: 30.0,
            ),
          ),
          centerTitle: true,
          backgroundColor: Colors.grey[800],
          actions: [
            IconButton(onPressed: () {
              showDialog(context: context, builder: (context) =>
                  Dialog(
                    child: SizedBox(
                      height: 200,
                      width: 200,
                      child: Column(
                        children: [
                          TextFormField(
                            decoration: InputDecoration(
                              filled: true,
                              labelText: 'product',
                              icon: Icon(Icons.star),
                            ),
                            controller: productController,
                            validator: (value){
                              if(value == null || value.isEmpty){
                                return 'Enter product name';
                              }
                              return null;
                            },
                          ),
                          Divider(
                            height: 20.0,
                            color: Colors.grey[800],
                          ),

                          ///Text Field
                          TextFormField(
                            decoration: InputDecoration(
                              filled: true,
                              labelText: 'price',
                              icon: Icon(Icons.star),
                            ),
                            keyboardType: TextInputType.number,
                            controller: prizeController,

                          ),
                          ElevatedButton(onPressed: () {
                            if (productController.text.isEmpty && prizeController.text.isEmpty){
                              const AlertDialog(
                                title: Text('Enter Value'),
                              );
                            } else{
                              setState(() {
                                setprodata(productController.text);
                                setpridata(prizeController.text);
                                productdata.add(Data(productController.text, prizeController.text));
                                productController.text = "";
                                prizeController.text = "";
                                Navigator.of(context).pop();
                              });
                            }
                          }, child:
                          const Text('Submit')),
                        ],
                      ),
                    ),
                  ),
              );
            }, icon: Icon(Icons.add))
          ],
        ),

        ///app Drawer
        drawer: Drawer(
          child: ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              UserAccountsDrawerHeader(
                decoration: BoxDecoration(
                    color: Colors.black45
                ),
                accountName: Text('Raj'),
                accountEmail: Text('[email protected]'),
                currentAccountPicture: CircleAvatar(
                  backgroundColor: Colors.orange,
                  child:
                  Text('R', style:
                  TextStyle(fontSize: 40),),
                ),
              ),
              ListTile(
                leading: Icon(Icons.home),
                title: Text('Home'),
                onTap: () {
                  Navigator.pop(context);
                },
              ),
              ListTile(
                leading: Icon(Icons.contact_mail),
                title: Text('Contact Us'),
                onTap: () {
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        ),

        ///Body of the app
        body: ListView.builder(
            itemCount: productdata.length,
            itemBuilder: (BuildContext context, int index) {
              return
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Expanded(
                        child: ListTile(
                      tileColor: Colors.cyan,
                      leading: Icon(Icons.star),
                      trailing: IconButton(onPressed: () {
                        showDialog(context: context, builder: (context) =>
                            AlertDialog(
                              title: Text('Delte this?'),
                              content: Text('Are you sure?'),
                              actions: <Widget>[
                                TextButton(onPressed: () {
                                  Navigator.pop(context);
                                }, child:
                                Text('Cancel')),
                                TextButton(onPressed: () {
                                  setState(() {
                                    productdata.remove(productdata[index]);
                                    Navigator.pop(context);
                                  });
                                }, child:
                                const Text('Delete', style:
                                TextStyle(
                                  color: Colors.black87,
                                  fontSize: 16,
                                ),))
                              ],
                            ));
                      }, icon: Icon(Icons.delete)),
                      title: Text(productdata[index].product!,
                        style:
                        TextStyle(
                          fontSize: 22,
                          fontWeight: FontWeight.bold,
                        ),),
                      onTap: () {
                        Navigator.of(context).push(MaterialPageRoute(
                            builder: (context) => Info(value: productdata[index])));
                      },

                    )),

                  ],
                );
            }),
      );
    }

  }



i tried using shared preferences but i am not geting any value.

here my info page where i want to get values:

import 'package:flutter/material.dart';
import 'package:list_ex/home.dart';
import 'package:list_ex/product.dart';
import 'package:list_ex/shared_pref.dart';
import 'package:shared_preferences/shared_preferences.dart';


class Info extends StatelessWidget {
  final Data value;
  var pro;
  var pri;

  @override
  void initState() {
    getprodata();
    getpridata();
  }

  Info({Key? key, required this.value}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var pridata;
    var prodata;
    return Scaffold(
        appBar: AppBar(
          title: Text('Product Info'),
          centerTitle: true,
          backgroundColor: Colors.grey[800],
        ),
        body: Center(
          child: Card(
            color: Colors.cyan,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20.0)),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                ListTile(
                  // ignore: prefer_interpolation_to_compose_strings
                  title: Text('Product Name:'   value.product!, style:
                  TextStyle(
                    fontSize: 20,
                  ),),
                  subtitle: Text('Price:'   value.prize!, style:
                  TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold
                  ),),

                ),
              ],
            ),
          ),
        )
    );
  }


}

CodePudding user response:

first import shared_preferences library into your project.

make instance of preference.

final prefs = await SharedPreferences.getInstance();

now write or store data into preference

counter is for Key and 10 is value

await prefs.setInt('counter', 10);

what ever key you will give here it will store data into that key only through this key you can get you data.

you can store any type of data like for int type you have to use setInt for String type use setString() and so on..

now you can get this data through get

final int? counter = prefs.getInt('counter');

in getInt() just pass key that you want to get data. and use only one instance in every screen of you project to write and get data.

for more information see https://pub.dev/packages/shared_preferences

  • Related