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!
how do I get this model from another screen ?