问题
Is there any library available to save object and restore it.
In android java we using Gson to do this but in flutter there is no Gson
回答1:
A library like GSON won't be possible in Flutter, since Flutter doesn't support code reflection. Reflection interferes with tree shaking which flutter needs to clean out unused code and give a compact app.
more on the topic and alternatives here
You can use this site to convert your JSONs to class and it prepares the toJson fromJson methods automatically.
回答2:
You have for this the built_value package.
With that you can Serialize and Deserialize objects.
First you will need to declare the object:
part 'foo.g.dart';
abstract class Foo
implements Built<Foo, FooBuilder>{
static Serializer<Foo> get serializer => _$fooSerializer;
String get fooValue;
@nullable int get creationDate;
Foo._();
factory Foo([updates(FooBuilder b)]) = _$Foo;
}
All the object will have to follow this frame model:
- Being an abstract class implmenting Built
- Declaring a static
Serializer
getter value
- Declaring the _()
- Declaring a factory
- Declaring a .part
at the top, so that we can generate a model file
I recommend to you copying the class and changing only the names and the model.
Then, if you want to serialize it, you have to create a Serializer
class
import 'package:built_collection/built_collection.dart';
import 'package:built_value/serializer.dart';
import 'package:built_value/standard_json_plugin.dart';
part 'serializers.g.dart';
@SerializersFor(const [
Foo // declare here all the classes to be serialized
])
Serializers serializers = _$serializers;
Serializers standardSerializers =
(serializers.toBuilder()
..add(CustomDateTimeSerializer()) // delcare here custom plugins
..addPlugin(StandardJsonPlugin())
).build();
}
As a bonus, I will post here a custom Serializer for time values:
/// Serializer for [DateTime] using Milliseconds instead of MicroSeconds
///
/// An exception will be thrown on attempt to serialize local DateTime
/// instances; you must use UTC.
class CustomDateTimeSerializer implements PrimitiveSerializer<DateTime> {
final bool structured = false;
@override
final Iterable<Type> types = new BuiltList<Type>([DateTime]);
@override
final String wireName = 'DateTime';
@override
Object serialize(Serializers serializers, DateTime dateTime,
{FullType specifiedType = FullType.unspecified}) {
if (!dateTime.isUtc) {
throw new ArgumentError.value(
dateTime, 'dateTime', 'Must be in utc for serialization.');
}
return dateTime.microsecondsSinceEpoch / 1000;
}
@override
DateTime deserialize(Serializers serializers, Object serialized,
{FullType specifiedType = FullType.unspecified}) {
final microsecondsSinceEpoch = serialized as int;
return new DateTime.fromMicrosecondsSinceEpoch(microsecondsSinceEpoch * 1000 * 1000,
isUtc: true);
}
}
After this, make sure to run the following in the terminal, on the root of your project folder:
flutter packages pub run build_runner watch
The log will help you find errors that you have in your code.
Then, you will have the .g
files for each model.
You can now serialize the object with:
import 'dart:convert' as json;
//...
var jsonEncoded = json.jsonEncode(standardSerializers.serializeWith(Foo.serializer, foo));
Bonus tip: this can also be used to have a builder for your object:
var foo = Foo((b) => b
..fooValue = "foo"
..creationDate = DateTime.now()
);
回答3:
Future<void> saveLoginObj(LoginResponse obj) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
try {
String resp = json.encode(obj);
await prefs.setString('apiToken',resp);
// Get
String token = prefs.getString('apiToken');
var decoded = json.decode(token);
LoginResponse loginResponse = LoginResponse.fromJson(decoded);
} on Exception catch (e) {
print(e);
throw Exception("Error on save token");
}
}
回答4:
I am using this website and it saves my time
no need to think just past the JSON code here then it will generate the prefect dart class code
https://app.quicktype.io/
来源:https://stackoverflow.com/questions/54036514/what-is-the-equlent-libary-avalable-in-flutter-dart-like-gson-in-java