Flutter – How to save JSON object to SharedPreferences

shared_preferences is one of the most popular packages that you can use to persist data locally. This package provides us setX methods to save data and getX methods to retrieve the persisted values.

SharedPreferences sharedPrefs = await SharedPreferences.getInstance();
sharedPrefs.setInt('key', 1);
sharedPrefs.getInt('key');

However, if you want to save JSON object, you can not simply save your JSON object as String. In this post we will learn how to save JSON object to SharedPreferences.

Assume we have a JSON like below and we need to save it locally for using later:

{
  "info": {
    "id": "1",
    "name": "Coflutter",
    "avatar": "https://example.com/coflutter.jpg"
  },
  "token": "xxx"
}


1. Create 2 models User and Info

Don’t forget to override toString() method to have a beautiful output like what we discuss in previous post.

class Info {
  String id;
  String name;
  String avatar;

  Info({required this.id, required this.name, required this.avatar});

  factory Info.fromJson(Map<String, dynamic> json) {
    String id = json['id'];
    String name = json['name'];
    String avatar = json['avatar'];

    return Info(id: id, name: name, avatar: avatar);
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['avatar'] = this.avatar;
    return data;
  }

  @override
  String toString() {
    return '"info" : { "id": $id, "name": $name, "avatar": $avatar}';
  }
}
class User {
  Info info;
  String token;

  User({required this.info, required this.token});

  factory User.fromJson(Map<String, dynamic> json) {
    Info info = Info.fromJson(json['info']);
    String token = json['token'];

    return User(info: info, token: token);
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['info'] = this.info.toJson();
    data['token'] = this.token;
    return data;
  }

  @override
  String toString() {
    return '"user" : {${info.toString()}, "token": $token}';
  }
}


2. Save user data to local storage

Future<void> saveUserInfo() async {
    final User user = User.fromJson({
      'info': {
        'id': '1',
        'name': 'Coflutter',
        'avatar': 'https://example.com/coflutter.jpg'
      },
      'token': 'xxx'
    });

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    bool result = await prefs.setString('user', jsonEncode(user));
    print(result);
  }


3. Retrieve data when needed

Future<User> getUserInfo() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();

    Map<String, dynamic> userMap = {};
    final String? userStr = prefs.getString('user');
    if (userStr != null) {
      userMap = jsonDecode(userStr) as Map<String, dynamic>;
    }

    final User user = User.fromJson(userMap);
    print(user);
    return user;
  }


Put it all to the demo

import 'dart:convert';

// You may need to change the import to make it works
import 'package:coflutter/flutter/shared_preferences/json_with_shared_preferences/user.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(SharedPrefsJsonDemo());

class SharedPrefsJsonDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Coflutter - SharedPrefs with Json',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Coflutter - SharedPrefs with Json'),
          backgroundColor: const Color(0xffae00f0),
        ),
        body: DemoScreen(),
      ),
    );
  }
}

class DemoScreen extends StatefulWidget {
  @override
  _DemoScreenState createState() => _DemoScreenState();
}

class _DemoScreenState extends State<DemoScreen> {
  @override
  void initState() {
    super.initState();

    saveUserInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: getUserInfo,
        child: Text('Show user info'),
      ),
    );
  }

  Future<User> getUserInfo() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();

    Map<String, dynamic> userMap = {};
    final String? userStr = prefs.getString('user');
    if (userStr != null) {
      userMap = jsonDecode(userStr) as Map<String, dynamic>;
    }

    final User user = User.fromJson(userMap);
    print(user);
    return user;
  }

  Future<void> saveUserInfo() async {
    final User user = User.fromJson({
      'info': {
        'id': '1',
        'name': 'Coflutter',
        'avatar': 'https://example.com/coflutter.jpg'
      },
      'token': 'xxx'
    });

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    bool result = await prefs.setString('user', jsonEncode(user));
    print(result);
  }
}

Output

flutter: true
flutter: "user" : {"info" : { "id": 1, "name": Coflutter, "avatar": https://example.com/coflutter.jpg}, "token": xxx}


If you are looking for a developer or a team to build you next projects, please Drop us your request!

Tagged : / /
Subscribe
Notify of
guest

9 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
tiffany sailar
1 year ago

how do I get this model from another screen ?

Glenn
2 years ago

This code doesn’t seem to be valid anymore due to the not-null requirements, what version of flutter/dart has this been ran against ? I assume the fix is declaring the private variables as late.

Abhishek anand
Abhishek anand
2 years ago

kuch v type kr deta

tina
2 years ago

O I do not think you want my comments on here. but Id like to see you in person

Aquiles Oliveira
Aquiles Oliveira
3 years ago

You helped a lot with your publication!!!
Thanks man!!!

faisal
faisal
3 years ago

good job brother !

Dangdat
Dangdat
3 years ago

This is exactly what I want to implement, but I have a very nested JSON file than this. I will appreciate if you help me with the github link or help me out. Thank you.

9
0
Would love your thoughts, please comment.x
()
x