“This is the second day of my participation in the November Gwen Challenge. Check out the event details: The Last Gwen Challenge 2021”

preface

Learning is always enjoyable. Today I’m going to share with you serialization and persistence in DART development.

Dart object to Map

Before we talk about serialization, let’s look at the conversion between Dart objects and Map data structures.

The example is simple: the toMap method converts an object to a Map and the fromMap method converts a Map to an object.

class Teacher {
  final String name;
  final List<Student> students;

  Teacher({
    required this.name,
    required this.students,
  });

  /// Notice that students is an array and needs to be traversed
  Map<String.dynamic> toMap() {
    return <String.dynamic> {"name": name,
      "students": students.map((e) => e.toMap()).toList(),
    };
  }

  factory Teacher.fromMap(Map map) {
    return Teacher(
      name: map["name"],
      students:
          (map["students"] as List).map((e) => Student.fromMap(e)).toList(), ); }}class Student {
  final String name;

  Student({required this.name});

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

  factory Student.fromMap(Map map) {
    return Student(
      name: map["name"]); }}Copy the code

Key point: Map traversal is required when member variables are array objects

Serialization & deserialization

First, to clarify the concept, serialization refers to converting Dart objects to and from JSON data. In real development, we often do this by converting the Dart object to a Map object, and then converting the Map object to JSON.

For example, 🌰

import 'dart:convert' as json;
Copy the code
Student s1 = Student(name: "3");
Student s2 = Student(name: "Small 2");
Teacher teacher = Teacher(name: "Head teacher", students: [
  s1,
  s2,
]);
Copy the code
///Dart object to Map
Map map = teacher.toMap();
///Serialized JSON string
String jsonString = json.jsonEncode(map);
///deserialization
Map<String.dynamic> result = json.jsonDecode(jsonString);
///Turn the JSON object
Teacher teacher = Teacher.fromMap(result);
Copy the code

Teacher.tomap ().toString() is not directly converted into a string, why do we need to use jsonEncode to transfer?

Teacher.tomap ().tostring ()

[{name: zhang SAN}, {name: Li Si}]}Copy the code

JsonEncode (map) :

{"name":"Finin"."students": [{"name":"Zhang"}, {"name":"Bill"}}]Copy the code

The result of toString() is a map structured string, while json.jsonencode (map) is a JSON string.

persistence

We often persist the object to string in SharePreference.

Introduce support packages in pubspec.yaml

shared_preferences: 2.09.
Copy the code

Create SharepreferenceTool as a utility class

abstract class SharePreferenceTool {
  static late SharedPreferences _sp;
  static bool _inited = false;

  static SharedPreferences get sp => _sp;

  static bool get inited => _inited;

  static Future<bool> init() async {
    _sp = await SharedPreferences.getInstance();
    _inited = true;
    return true; }}Copy the code

How to use it? Come a chestnut 🌰

Map map = teacher.toMap();
Copy the code

String jsonString = json.jsonEncode(map);

if(! SharePreferenceTool.inited){await SharePreferenceTool.init();
}
///Save jsonString sp
SharePreferenceTool.sp.setString("teacherSp", jsonString);
///Get jsonString from sp via key
String json = SharePreferenceTool.sp.getString("teacherSp")! ;/// Turn jsonString map
Map<String.dynamic> result = json.jsonDecode(json);
Copy the code