A more easy way to do Flutter JSON serialization and deserialization.
Add a dependency on hn_easy_model in your pubspec.
dependencies:
hn_easy_model: any
build_runner: any
Create a dart file to aggregate headers. For example you created a dart file named easy_model_headers.dart
.
Create a file named build.yaml
,in the same path with pubspec.yaml
. The content is as follows. lib/easy_model_headers.dart
replace with right path.
targets:
$default:
builders:
hn_easy_model:
generate_for:
- lib/easy_model_headers.dart
Switch to the command line run flutter packages pub run build_runner build
. It will create a file named easy_model_headers.hneasymodel.dart
.
At the beginning of the program import previous file import 'easy_model_headers.hneasymodel.dart';
. Execute code initializeEasyModel();
Model must extends HNEasyModel
and annotation model with @hn_easy_model
.
@hn_easy_model
class Person extends HNEasyModel {
int age;
double weight;
String name;
bool married;
Person mother;
Person father;
List<Person>friends;
}
Use hn_easyInitFromJson
method, example model().hn_easyInitFromJson(map);
Use hn_easyToJson
method, example model.hn_easyToJson();
While model change you need run flutter packages pub run build_runner build
. If there is an error you can run flutter packages pub run build_runner build --delete-conflicting-outputs
or just delete easy_model_headers.hneasymodel.dart
file.
- int
- double
- bool
- String
- Custom model (need annotation with@hn_easy_model)
- Map (cannot specify type)
- List (you need specify type,support custom model annotation with @hn_easy_model)
- var dynamic (only support int、double、bool、String)
zhnnnnn, [email protected]
hn_easy_model is available under the MIT license. See the LICENSE file for more info.