text stringlengths 1 474 |
|---|
generate the encoding boilerplate for you. After some initial setup, |
you run a file watcher that generates the code from your model classes. |
For example, json_serializable and built_value are these |
kinds of libraries.This approach scales well for a larger project. No hand-written |
boilerplate is needed, and typos when accessing JSON fields are caught at |
compile-time. The downside with code generation is that it requires some |
initial setup. Also, the generated source files might produce visual clutter |
in your project navigator.You might want to use generated code for JSON serialization when you have a |
medium or a larger project. To see an example of code generation based JSON |
encoding, see Serializing JSON using code generation libraries.<topic_end> |
<topic_start> |
Is there a GSON/Jackson/Moshi equivalent in Flutter? |
The simple answer is no.Such a library would require using runtime reflection, which is disabled in |
Flutter. Runtime reflection interferes with tree shaking, which Dart has |
supported for quite a long time. With tree shaking, you can “shake off” unused |
code from your release builds. This optimizes the app’s size significantly.Since reflection makes all code implicitly used by default, it makes tree |
shaking difficult. The tools cannot know what parts are unused at runtime, so |
the redundant code is hard to strip away. App sizes cannot be easily optimized |
when using reflection.Although you cannot use runtime reflection with Flutter, |
some libraries give you similarly easy-to-use APIs but are |
based on code generation instead. This |
approach is covered in more detail in the |
code generation libraries section.<topic_end> |
<topic_start> |
Serializing JSON manually using dart:convert |
Basic JSON serialization in Flutter is very simple. Flutter has a built-in |
dart:convert library that includes a straightforward JSON encoder and |
decoder.The following sample JSON implements a simple user model. |
<code_start>{ |
"name": "John Smith", |
"email": "john@example.com" |
}<code_end> |
With dart:convert, |
you can serialize this JSON model in two ways.<topic_end> |
<topic_start> |
Serializing JSON inline |
By looking at the dart:convert documentation, |
you’ll see that you can decode the JSON by calling the |
jsonDecode() function, with the JSON string as the method argument. |
<code_start>final user = jsonDecode(jsonString) as Map<String, dynamic>; |
print('Howdy, ${user['name']}!'); |
print('We sent the verification link to ${user['email']}.');<code_end> |
Unfortunately, jsonDecode() returns a dynamic, meaning |
that you do not know the types of the values until runtime. With this approach, |
you lose most of the statically typed language features: type safety, |
autocompletion and most importantly, compile-time exceptions. Your code will |
become instantly more error-prone.For example, whenever you access the name or email fields, you could quickly |
introduce a typo. A typo that the compiler doesn’t know about since the |
JSON lives in a map structure.<topic_end> |
<topic_start> |
Serializing JSON inside model classes |
Combat the previously mentioned problems by introducing a plain model |
class, called User in this example. Inside the User class, you’ll find:With this approach, the calling code can have type safety, |
autocompletion for the name and email fields, and compile-time exceptions. |
If you make typos or treat the fields as ints instead of Strings, |
the app won’t compile, instead of crashing at runtime.user.dart |
<code_start>class User { |
final String name; |
final String email; |
User(this.name, this.email); |
User.fromJson(Map<String, dynamic> json) |
: name = json['name'] as String, |
email = json['email'] as String; |
Map<String, dynamic> toJson() => { |
'name': name, |
'email': email, |
}; |
}<code_end> |
The responsibility of the decoding logic is now moved inside the model |
itself. With this new approach, you can decode a user easily. |
<code_start>final userMap = jsonDecode(jsonString) as Map<String, dynamic>; |
final user = User.fromJson(userMap); |
print('Howdy, ${user.name}!'); |
print('We sent the verification link to ${user.email}.');<code_end> |
To encode a user, pass the User object to the jsonEncode() function. |
You don’t need to call the toJson() method, since jsonEncode() |
already does it for you. |
<code_start>String json = jsonEncode(user);<code_end> |
With this approach, the calling code doesn’t have to worry about JSON |
serialization at all. However, the model class still definitely has to. |
In a production app, you would want to ensure that the serialization |
works properly. In practice, the User.fromJson() and User.toJson() |
methods both need to have unit tests in place to verify correct behavior.info |
The cookbook contains a more comprehensive worked example of using |
JSON model classes, using an isolate to parse |
the JSON file on a background thread. This approach is ideal if you |
need your app to remain responsive while the JSON file is being |
decoded.However, real-world scenarios are not always that simple. |
Sometimes JSON API responses are more complex, for example since they |
contain nested JSON objects that must be parsed through their own model |
class.It would be nice if there were something that handled the JSON encoding |
and decoding for you. Luckily, there is!<topic_end> |
<topic_start> |
Serializing JSON using code generation libraries |
Although there are other libraries available, this guide uses |
json_serializable, an automated source code generator that |
generates the JSON serialization boilerplate for you.info |
Choosing a library: |
You might have noticed two Flutter Favorite packages |
on pub.dev that generate JSON serialization code, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.