使用json_serializable插件生成模板代码 1.添加依赖库 打开跟目录pubspec.yaml文件添加依赖库:
dependencies:json_annotation: ^4.4.0//注解依赖
dev_dependencies: json_serializable: ^6.1.4//json格式化 build_runner: ^1.6.1
2.利用json生成模板代码可以使用网页https://caijinglong.github.io/json2dart/index.html
import 'package:json_annotation/json_annotation.dart';//这个名字一定要跟模板代码的文件名一致part 'category_mode.g.dart';@JsonSerializable()class CategoryBean extends Object { @JsonKey(name: 'categories') List categories; @JsonKey(name: 'message') String message; CategoryBean(this.categories,this.message,); factory CategoryBean.fromJson(Map srcJson) => _$CategoriesBeanFromJson(srcJson); Map toJson() => _$CategoriesBeanToJson(this);}@JsonSerializable()class Categories extends Object { @JsonKey(name: 'category_id') int categoryId; @JsonKey(name: 'image') String image; @JsonKey(name: 'parent_id') int parentId; @JsonKey(name: 'name') String name; @JsonKey(name: 'original_image') String originalImage; @JsonKey(name: 'children') List children; Categories(this.categoryId,this.image,this.parentId,this.name,this.originalImage,this.children,); factory Categories.fromJson(Map srcJson) => _$CategoriesFromJson(srcJson); Map toJson() => _$CategoriesToJson(this);}@JsonSerializable()class Children extends Object { @JsonKey(name: 'category_id') int categoryId; @JsonKey(name: 'image') String image; @JsonKey(name: 'parent_id') int parentId; @JsonKey(name: 'name') String name; @JsonKey(name: 'original_image') String originalImage; @JsonKey(name: 'children') List children; Children(this.categoryId,this.image,this.parentId,this.name,this.originalImage,this.children,); factory Children.fromJson(Map srcJson) => _$ChildrenFromJson(srcJson); Map toJson() => _$ChildrenToJson(this);}
3.在运行打开Terminal窗口运行命令
flutter packages pub run build_runner build
4.等待运行成功后会自动帮你新建一个刚刚模板代码category_mode.g.dart的category_mode.g.dart文件 使用实例:
final data = []; Future call() => get(Uri.parse(ServiceUrl.category)).then((value) { Map dataMap = json.decode(value.body); var bean = CategoryBean.fromJson(dataMap); data.addAll(bean.categories); });