flutter 序列化
If you intend to save user data to the shared preferences or local storage in your Flutter application, you will need to serialize it manually.
如果打算将用户数据保存到Flutter应用程序中的共享首选项或本地存储中,则需要手动对其进行序列化。
This is because both methods only support a limited selection of primitive object types and your object will probably not fall into any category. To do this we will be using the dart:convert decoder with its jsonEncode/jsonDecode methods, so make sure to import it into your project.
这是因为这两种方法仅支持有限的原始对象类型选择,并且您的对象可能不会属于任何类别。 为此,我们将使用dart:convert解码器及其jsonEncode / jsonDecode方法,因此请确保将其导入到您的项目中。
To do this, import the class in your main dart file:
为此,将类导入到您的主dart文件中:
import 'dart:convert';
如何在Dart中建立模型类 (How to build a Model Class in Dart)
To allow our object to become enabled for decoding/encoding we first need to create a Model class for it. This class will represent the object and it’s fields and have the important methods which will do the heavy work of encoding/decoding. The first one is called fromJson and the second one is called toJson. We will show various examples of complex objects and how to serialize them, but for the beginning, we’ll start with a simple one.
为了使我们的对象能够进行解码/编码,我们首先需要为其创建一个Model类。 此类将表示对象及其字段,并具有将进行繁重的编码/解码工作的重要方法。 第一个称为fromJson ,第二个称为toJson 。 我们将展示复杂对象的各种示例以及如何序列化它们,但首先,我们将从一个简单的示例开始。
We’ll imagine we have a doughnut shop, where we have various doughnuts. Each d