how to save data model object data in sharedpreferences flutter

Hi Guys, Welcome to Proto Coders Point.

In this Flutter tutorial, We will learn how to store a data model object data in sharedPreferences in flutter.

Note: Firstly you need to serialize data to JSON String before saving it & the de-serialize it after reading.

Read this flutter article on JSON and serialization in flutter
https://flutter.dev/docs/development/data-and-backend/json to learn more in details.


Let’s Serialize JSON inside model class ‘User’

In ‘User’ data model class you will find 3 fields: name, email, phone & it also has a constructor & a method as below:

User.fromJson(): A constructor used for constructing a user instance from a Map structure.

toJson(): A method, used to convert user instance into a map.

User.dart

class User {
  final String name;
  final String email;
  final String phone;

  User(this.name, this.email,this.phone);

  //constructor that convert json to object instance
  User.fromJson(Map<String, dynamic> json) : name = json['name'],  email = json['email'],phone = json['phone'];

  //a method that convert object to json
  Map<String, dynamic> toJson() => {
    'name': name,
    'email': email,
    'phone':phone
  };
}

Saving object data in sharedPreferences

To save data model object, we must first convert it into a JsonString.

After converting model object data into JSON String, we can easily store it a String datatype.

then, we are storing jsonString into a shared_Preferences with key-value pairs.

 void storeUserData(){

    //store the user entered data in user object
    User user1 = new User(_name.text, _email.text);

    // encode / convert object into json string
    String user = jsonEncode(user1);

    print(user);

    //save the data into sharedPreferences using key-value pairs
    sharedPreferences.setString('userdata', user);
    
  }

Reading the data from shared_preferences

Now, you need to get the data stored in sharedPreferences, so fetch the data from sharedPreferences & convert the JsonString into Map Structure using jsonDecode() method & then convert it back to User Instance Object.

& finally use object to get data from data model datatype
Eg: user.name, user.email, user.phone.

void initialGetSaved() async{
    sharedPreferences = await SharedPreferences.getInstance();
      
   // Read the data, decode it and store it in map structure
    Map<String,dynamic> jsondatais = jsonDecode(sharedPreferences.getString('userdata')!);

    //convert it into User object
    var user = User.fromJson(jsondatais);

    if(jsondatais.isNotEmpty){
      print(user.name);
      print(user.email);
      //set the sharedPreferences saved data to TextField
      _name.value =  TextEditingValue(text: user.name);
      _email.value =  TextEditingValue(text: user.email);
      _phone.value =  TextEditingValue(text: user.phone);
    }
    
  }

How to convert User object data to json string and store in shared Preferences

Complete App implementation starts here

Let’s create a form in flutter, where a user can enter his name, email & phone(this is just for a example i have took 3 field).

Start with creating a new flutter project in your favorite IDE, I use android studio to build flutter apps( you can use any IDE).

1. Add Shared Preferences dependencies

As we need to save user entered data from TextField in flutter, we will make use of sharedpreferences to save the users data in app.

add sharedpreferences package into your flutter project.

In project > pubspec.yaml file.

In pubspec.yaml, under dependencies section add shared_preferences package.

dependencies:
  shared_preferences: #any version else keep empty it will take latest version

& then hit pub get or run flutter pub get commend in IDE Terminal.

2. Create a Data Model class ‘ User’

User.dart

class User {
  final String name;
  final String email;
  final String phone;

  User(this.name, this.email,this.phone);

  //constructor that convert json to object instance
  User.fromJson(Map<String, dynamic> json) : name = json['name'],  email = json['email'],phone = json['phone'];

  //a method that convert object to json
  Map<String, dynamic> toJson() => {
    'name': name,
    'email': email,
    'phone':phone
  };
}

3. UI – TextField Form Entered data will be saved until final submission

In main.dart page, we have 3 textfield, a Save Button & a submit button

3 TextField: user can enter name, email, phone.

Save Button: Saves the data entered in textfield for future, suppose if user leaves the app before final submission, After save button is press, the entered data in TextField will get saved and still exist even if user re-visit app in future.

Submit button: The submit will simply erase all the data from TextField & sharedpreferences will get cleared.

main.dart complete code

import 'dart:convert';

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

void main() async{
  await GetStorage.init();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
      
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {


  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


  late SharedPreferences sharedPreferences;
  
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initialGetSaved();
  }

  void initialGetSaved() async{
    sharedPreferences = await SharedPreferences.getInstance();
    
    // Read the data, decode it and store it in map structure
    Map<String,dynamic> jsondatais = jsonDecode(sharedPreferences.getString('userdata')!);

    var user = User.fromJson(jsondatais);

    if(jsondatais.isNotEmpty){
      print(user.name);
      print(user.email);

      _name.value =  TextEditingValue(text: user.name);
      _email.value =  TextEditingValue(text: user.email);
      _phone.value =  TextEditingValue(text: user.phone);
    }

  }

  void storeUserData(){

    //store the user entered data in user object
    User user1 = new User(_name.text, _email.text,_phone.text);

    // encode / convert object into json string
    String user = jsonEncode(user1);

    print(user);

    //save the data into sharedPreferences using key-value pairs
    sharedPreferences.setString('userdata', user);

  }


  TextEditingController _name = new TextEditingController();
  TextEditingController _email = new TextEditingController();
  TextEditingController _phone = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Save DataModel Data JSON'),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('Full Form',style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),),
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Container(
                  height: 50,
                  child: TextField(
                    controller: _name,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Enter name'
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Container(
                  height: 50,
                  child: TextField(
                    controller: _email,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Enter Email'
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Container(
                  height: 50,
                  child: TextField(
                    controller: _phone,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Enter Phone'
                    ),
                  ),
                ),
              ),
              ElevatedButton(onPressed: (){
                storeUserData();
              }, child: Text('SAVE')),
              ElevatedButton(onPressed: (){
                _name.value =  TextEditingValue(text: '');
                _email.value =  TextEditingValue(text: '');
                _phone.value =  TextEditingValue(text: '');
                sharedPreferences.remove('userdata');
              }, child: Text('SUBMIT'))
            ],
          ),
        ),
      ),
    );
  }
}

Shared Preferences alternative in flutter