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({this.id, this.name, this.avatar});

  Info.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    avatar = json['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}';
  }
}
import 'package:coflutter/package/shared_preferences/info.dart';

class User {
  Info info;
  String token;

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

  User.fromJson(Map<String, dynamic> json) {
    info = json['info'] != null ? Info.fromJson(json['info']) : null;
    token = json['token'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    if (this.info != null) {
      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>;
    }

    if (userMap != null) {
      final User user = User.fromJson(userMap);
      print(user);
      return user;
    }
    return null;
  }


Put it all to the demo

import 'dart:convert';

import 'package:coflutter/package/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: RaisedButton(
        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>;
    }

    if (userMap != null) {
      final User user = User.fromJson(userMap);
      print(user);
      return user;
    }
    return null;
  }

  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 : / /
5 3 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x