Dart entity class format

class CategoryMo { String name; int count; CategoryMo({this.name, this.count}); FromJson (map <String, dynamic> json) {name = json['name']; count = json['count']; ToJson () {final map <String, dynamic> data = new map <String, dynamic>(); data['name'] = this.name; data['count'] = this.count; return data; }}Copy the code

Scheme 1: handwriting entity class

person.json

{
  "name": "Jack",
  "age": 20
}
Copy the code

Model transformation and usage

var personMap = {
  "name": "Jack",
  "age": 20
};
Person person = Person.fromJson(personMap);
print('name:${person.name}');
print('age:${person.age}');
Copy the code

Scenario 2: Productivity tool: The JSON-to-DART plug-in automatically generates entity classes

Scenario 3: Productivity tools: JSON_ serializable usage techniques

  • Installing a plug-in
dependencies: ... Dio: ^3.0.10 json_annotation: ^3.1.0 dev_dependencies:... Json_serializable: ^ 3.5.0 build_runner: ^ 1.0.0Copy the code
  • Configuring entity Classes
{
    "code": 0,
    "method": "GET",
    "requestPrams": "dd"
}
Copy the code
import 'package:json_annotation/json_annotation.dart'; // result.g.art will automatically generate part 'result.g.art' after we run the build command; /// This annotation tells the generator, @jSonSerialIZABLE () class Result {// Define constructor Result(this.code, this.method, this.requestPrams); // define the field int code; String method; String requestPrams; Factory ResultFromJson(Map<String, dynamic> json) => _$ResultFromJson(json); Map<String, dynamic> toJson() => _$ResultToJson(this); }Copy the code

Because the entity class generation code does not yet exist, it is normal for the above code to indicate some errors

  • Execute build to generate the entity class
flutter packages pub run build_runner build
Copy the code

How to choose