This model generator can be used to generate JsonSerializable models
flutter packages run model_generator
By default, the model generator looks for the model yaml file in model_generator/config.yaml. If you want to overwrite this, specify it in your pubspec.yaml file by
using config_path. Example of the pubspec.yaml file if you want to use a custom model file location:
model_generator:
config_path: my_model_dir/config.yamlYou can also specify a command line parameter to override the location for a single run. For this, use the --path command line parameter. Example:
flutter packages run model_generator --path my_other_model_dir/config.yamlNote: Since version 6.1.0, instead of a single model file, you can specify a directory containing multiple model files.
The generator will then generate models for all .yaml (or .yml) files in the directory. References across files are supported.
Example of the pubspec.yaml file if you want to use a custom base_directory for all your models Default is /lib/model you can override it for all your models like this:
model_generator:
base_directory: custom_modelsthis will write all your models to /lib/custom_models
path will be added after the base_directory
If you are using fvm for managing your flutter version. You can add an option to the model generator as well to run with fvm. add an option use_fvm and set it to true. (by
default it is set to false)
model_generator:
use_fvm: trueIf you want the generated models to include code for == and hashCode, you can turn it on in pubspec.yaml. Defaults to false. All fields are taken into consideration for the
generated code.
model_generator:
equals_and_hash_code: trueor to override the values per object:
UserModel:
path: webservice/userequals_and_hash_code: falseproperties:
id: intIf you wish to ignore certain fields when generating the == and hashCode methods, you can mark those fields with ignore_equality: true.
Note: Models with all fields ignored will report a zero hash code and equal only on identity
UserModel:
path: webservice/userequals_and_hash_code: falseproperties:
id:
type: intignore_equality: trueinclude: StringBy default json_serializable will not generate the toJson methods on an other json_serializable object or list or map. With the model_generator we can enable this by default since 5.0.0 You can override it at a global level:
model_generator:
explicit_to_json: falseor to override the values per object:
UserModel:
path: webservice/userexplicit_to_json: falseproperties:
id: intIf you want the generated models to include generated toString code, you can turn it on in pubspec.yaml. Defaults to false. All fields are taken into consideration for the
generated code.
model_generator:
to_string: trueor to override the values per object:
UserModel:
path: webservice/userto_string: falseproperties:
id: intIf you wish for extra import statements in the generated files and/or extra annotations on the generated model classes, you can specify those in pubspec.yaml
model_generator:
extra_imports:
- 'package:flutter/foundation.dart'extra_annotations:
- '@immutable'or to override the values per object:
UserModel:
path: webservice/userextra_imports:
extra_annotations:
- '@someAnnotation'properties:
id: intSince version 5.6.0 default values are supported for properties. You can specify a default value for both required and optional properties by adding default_value: ... to the
property definition.
Note: Default values are taken exactly how they are specified in the yaml file, this means for example that you will need to quote strings correctly, ensure imports are there, ensure the value is a constant, ...
UserModel:
path: webservice/userextra_imports:
extra_annotations:
- '@someAnnotation'properties:
id:
type: intdefault_value: 1name:
type: Stringdefault_value: "'an example quoted string'"Since version 5.9.0 fields with default values can accept null values in json. In which case the default value will be used instead.
If you wish to control this behaviour, you can add disallow_null_for_defaults: true to either the model_generator config or the model property. Alternatively you can specify
the behaviour per field by using disallow_null.
Example:
model_generator:
disallow_null_for_defaults: trueExample 2:
UserModel:
path: webservice/userdisallow_null_for_defaults: trueproperties:
id:
type: intdefault_value: 1name:
type: Stringdefault_value: "'an example quoted string'"Example 3:
UserModel:
path: webservice/userproperties:
id:
type: intdefault_value: 1name:
type: Stringdefault_value: "'an example quoted string'"disallow_null: trueIf you want your models to generate code that can be used in combination with generics. use this:
model_generator:
generate_for_generics: trueor to override the default generate_for_generics value in the pubspec.yaml
UserModel:
path: webservice/usergenerate_for_generics: trueconverters:
- DateTimeConverterproperties:
id: intIf you want your models to expand any other model use extends:
Note: It is not supported to extend custom models
UserDetails:
path: webservice/userextends: UserModelproperties:
name: StringThe following framework types descriptors are known out of the box:
string/String
int/integer
bool/boolean
double
date/datetime
dynamic/object/any
array
map
Example of the model_generator/config.yaml file
UserModel:
path: webservice/userconverters:
- DateTimeConverterproperties:
id: intname: Stringsalary: doublesomething: dynamicisLoggedIn:
type: booldefault_value: falseroles: List<String>birthday: dateaddresses: List<Address>idToAddress: Map<String, Address>securityRole:
type: StringjsonKey: securityIndicatordynamicField: dynamicincludeIfNullField:
include_if_null: false #If this field is null, this field will not be added to your json object (used for PATCH models)type: StringignoreField:
ignore: false #This field is ignored in the to & from json methodstype: StringignoreFieldOnlyInFrom:
includeFromJson: false #This field is ignored in the from json methodtype: StringignoreFieldOnlyInTo:
includeToJson: false #This field is ignored in the to json methodtype: StringmutableField:
non_final: true #Field will not be marked finaltype: StringchangedAt:
type: DateTimeidToAddressList: Map<String, List<Address>>Address:
path: webservice/user #Can also be package:... and/or end with the actual file (.dart)properties:
street: String#Custom base_directoryCustomBaseDirectoryObject:
base_directory: custom_modelspath: webserviceproperties:
path: String#Custom json converter. Use with converters property on modelsDateTimeConverter:
type: json_converterpath: converter/In some cases, writing the full specification for simple fields is very verbose. Since 6.0.0 it is possible to write simple fields inline, without nesting below the field name, since 7.0.0 nested lists and list in maps is also supported:
UserModel:
properties:
id: intname: Stringage: intis_active: bool?created_at: DateTimeroles: List<string>customProperties: Map<String, Property>?customPropertiesList: Map<String, List<Property>>?since 7.0.0 inline types are supported now even when adding extra configuration:
before:
BookCase:
path: webservice/BookCasesproperties:
id: intbooks:
type: arrayitems:
type: Bookrequired: falseinclude_if_null: falsenow:
BookCase:
path: webservice/BookCasesproperties:
id: intbooks:
type: List<Book>?include_if_null: falseCurrently all basic types are supported, simple Lists and Maps (no nullable generic parameters) as well as references to other objects.
Items post-fixed with ? will be marked optional.
Add simple enums, the name of the enum value (MALE, FEMALE, X, Y) will be used when parsing from json
Gender:
path: webservice/usertype: enumvalues:
MALE:
FEMALE:
X:
Y:By default enums will be generated with a property called jsonValue. this is the value of the enum used when parsing from json. This will only be used when there isn't already a custom jsonValue defined using 'is_json_value: true' in the properties of the enum. To turn this behavior of you can use 'use_default_json_value: false'.
Gender:
path: webservice/useruse_default_json_value: falsetype: enumvalues:
MALE:
FEMALE:
X:
Y:Add enums with custom properties (currently supported types are int, double, bool and String)
Gender:
path: webservice/usertype: enumproperties:
abbreviation: Stringvalues:
MALE:
properties:
abbreviation: mFEMALE:
properties:
abbreviation: fX:
properties:
abbreviation: xY:
properties:
abbreviation: yDefine custom json key using is_json_value, the value of this property will then be used to parse from json
Gender:
path: webservice/usertype: enumproperties:
key:
type: Stringis_json_value: trueabbreviation: Stringvalues:
MALE:
properties:
key: maleabbreviation: mFEMALE:
properties:
key: femaleabbreviation: fX:
properties:
key: xabbreviation: xY:
properties:
key: yabbreviation: yOptional and default values are supported. If value isn't defined for a property then it will use the defaultValue. If a property is optional and no value is given it is null.
Gender:
path: webservice/usertype: enumproperties:
key:
type: Stringis_json_value: trueabbreviation:
type: Stringdefault_value: mlastName: String?values:
MALE:
properties:
key: maleFEMALE:
properties:
key: femaleabbreviation: fX:
properties:
key: xY:
properties:
key: ylastName: lastNameIt is possible to generate an extension for the enum that can turn the enum into it's corresponding jsonValue and the reverse.
Person:
path: test/enum/type: enumgenerate_extension: trueproperties:
jsonValue: is_json_value: truetype: intfirstName: StringlastName: Stringvalues:
MAN:
properties:
jsonKey: 1firstName: firstName1lastName: lastName1WOMAN:
properties:
jsonKey: 2firstName: firstName2lastName: lastName2The above configuration will generate an enum with this extension.
extensionPersonExtensiononPerson {
staticPerson?fromJsonValue(int value) =>Person.values.firstWhereOrNull((enumValue) => enumValue.jsonKey == value);
inttoJsonValue() => jsonKey;
}UnknownEnumTestObject:
path: webserviceproperties:
path:
unknown_enum_value: Xtype: GenderAs of v7.0.0 by default all fields will be converted into lowercase camelcase instead of uppercase like before. You can control this behavior globally for all enums or per-enum by setting the uppercase_enums property to false (
default) or true. This only affects the name of the enum when using it in dart code. the jsonValue will still be the name you type in the config.
model_generator:
uppercase_enums: trueor
UnknownEnumTestObject:
path: webserviceuppercase_enums: trueproperties:
path:Support for custom objects that are not generated by the model generator.
Paths are either local to the project, package specifications (package:...) or dart:core
CustomObject:
path: data/custom/type: custom factory {Model_Name}.fromJson(Map<String, dynamic> json) => _${Model_Name}FromJson(json);
Map<String, dynamic> toJson() => _${Model_Name}ToJson(this);
Support for custom objects but use fromJson & toJson instead of full object parsing:
CustomObjectFromToJson:
path: data/custom/type: custom_from_to_json{Model_Name} handle{Model_Name}FromJson(object) => {Model_Name}.fromJson(object);
{Original_Type} handle{Model_Name}ToJson({Model_Name} data) => data.toJson();
Support for custom objects but use fromJson & toJson instead of full object parsing:
UserModel:
path: webservice/userproperties:
description: The time at which the user has last updated his informationchangedAt:
type: datetimefromJson: handleFromJsonWithCustomCodetoJson: handleToJsonWithCustomCodeYou can specify custom json converters to be used for types that match
UserModel:
path: webservice/userconverters:
- DateTimeConverterproperties:
changedAt: DateTimeSpecify the custom JsonConverter object as a known type to resolve it
DateTimeConverter:
type: json_converterpath: converter/You can specify description on models, enum, fields and on enum entries. This description will be used verbatim to generate a code comment for that class/enum/field
Example for a class:
UserModel:
path: webservice/userdescription: The model holding user dataconverters:
- DateTimeConverterproperties:
description: The time at which the user has last updated his informationchangedAt: DateTimeExample for a enum:
Person:
path: test/enum/type: enumdescription: This is a enum of a personvalues:
MAN:
description: enum of a manWOMAN:
description: enum of a womanOTHER:
description: enum of a otherYou can specify static_create on objects or globally in the pubspec.yaml file. If this is specified, a static creator method called create will be generated referencing the
factory constructor. This static method can be used as a function reference. Defaults to false
UserModel:
path: webservice/userstatic_create: trueproperties:
changedAt: DateTimeRetrofit has added compute function support for decoding json payload in version 3.0.0. This requires top-level functions with a certain signature. You can have model generator
generate these for you by setting retrofit_compute: true in the pubspec.yaml file:
model_generator:
retrofit_compute: true