How to Store data as an object in shared preferences in flutter

How to Store Data as an Object in Shared Preferences in Flutter?

When designing the mobile application, you might want to save the custom object for future use, likewise, storing the user information when the application is closed and utilizing it again when it’s opened later. So, in this article, we will go through How to Store data as an object in shared preferences in Flutter?

Are you ready for the same? Let’s dive into the same.

How to Store data as an object in shared preferences in Flutter?

You need to serialize it to JSON before saving and deserialize it after reading. You can check flutter.dev.

You can store an object in Shared Preferences as Below:

SharedPreferences shared_User = await SharedPreferences.getInstance();
            Map<String, dynamic> decode_options = jsonDecode(jsonString);
            String user = jsonEncode(User.fromJson(decode_options));
            shared_User.setString('user', user);

SharedPreferences shared_User = await SharedPreferences.getInstance();
            Map<String, dynamic> userMap = jsonDecode(shared_User.getString('user'));
            var user = User.fromJson(userMap);

    class User {
      final String name;
      final String age;

      User({required this.name,required this.age});

      factory User.fromJson(Map<String, dynamic> parsedJson) {
        return new User(
            name: parsedJson['name'] ?? "",
            age: parsedJson['age'] ?? "");
      }

      Map<String, dynamic> toJson() {
        return {
          "name": this.name,
          "age": this.age
        };
      }
    }

To save the object to shared preferences:

SharedPreferences pref = await SharedPreferences.getInstance();
MapMap<String, dynamic> json = jsonDecode(jsonString);
String user = jsonEncode(UserModel.fromJson(json));
pref.setString('userData', user);

To fetch the object from shared preferences:

SharedPreferences pref = await SharedPreferences.getInstance();
Map<String, dynamic> json = jsonDecode(pref.getString('userData'));
var user = UserModel.fromJson(json);

You will need to import the below-mentioned packages:
Add the shared_preferences package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  shared_preferennces: ^2.0.7
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

The easiest way to create Model Follow our convert Json string to Json object in Flutter article.

When Getting Data from the API and Saving it Into Sharepreference

Getting Data from the API and Saving it Into Sharepreference with the Flutter will help you reduce the lengthy codes and supporting classes which are written in SQLite

 Future<UserDetails> UserInfo({String sesscode, regno}) async{
await Future.delayed(Duration(seconds: 1));
SharedPreferences preferences = await SharedPreferences.getInstance();
 var map = new Map<String, String>();
map["sesscode"] = sesscode;
map["regno"] = regno;

 var response = await http.post(Base_URL().user_info, body: map);
 Map decodedata = json.decode(response.body);
 if(decodedata != null){
  String user = jsonEncode(UserDetails.fromJson(decodedata));
  preferences.setString(SharePrefName.infoPref, user);
  return UserDetails.fromJson(decodedata);
}
  return null;
 }

You can call this function anywhere in your App

Future<UserDetails> getSavedInfo()async{
 SharedPreferences preferences = await SharedPreferences.getInstance();
 Map userMap = jsonDecode(preferences.getString(SharePrefName.infoPref));
  UserDetails user = UserDetails.fromJson(userMap);
  return user;
 }

Now, Call it inside a Class to get a username

Future<UserDetails> usd = getSavedInfo();
       usd.then((value){
         print(value.surname);
 });

Flutter Developers from Flutter Agency

Conclusion:

FlutterAgency.com is our dedicated and most trusted Platform for Flutter Technology, where we have Flutter mobile app developers with years of experience. They have a skill set in this platform and will deliver the best for your business. The portal is full of advanced resources related to Flutter like Flutter Widget Guide, Flutter Projects, Code libs, etc. Many visitors came to enhance their knowledge of Flutter development and get clear about it.

Connect with us at flutteragency.com. Flutteragency intends to provide the Flutter application with high quality. We give applications of the highest quality, and users can use them hassle-free.

Thanks for being with us on a Flutter Journey !!!

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *


ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields

✓ Valid number ✕ Invalid number