1.添加依赖库
打开跟目录pubspec.yaml 文件添加依赖库:
dependencies:
json_annotation: ^4.4.0
dev_dependencies:
json_serializable: ^6.1.4
build_runner: ^1.6.1
import 'package:json_annotation/json_annotation.dart';
part 'category_mode.g.dart';
@JsonSerializable()
class CategoryBean extends Object {
@JsonKey(name: 'categories')
List<Categories> categories;
@JsonKey(name: 'message')
String message;
CategoryBean(this.categories,this.message,);
factory CategoryBean.fromJson(Map<String, dynamic> srcJson) => _$CategoriesBeanFromJson(srcJson);
Map<String, dynamic> 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> children;
Categories(this.categoryId,this.image,this.parentId,this.name,this.originalImage,this.children,);
factory Categories.fromJson(Map<String, dynamic> srcJson) => _$CategoriesFromJson(srcJson);
Map<String, dynamic> 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<dynamic> children;
Children(this.categoryId,this.image,this.parentId,this.name,this.originalImage,this.children,);
factory Children.fromJson(Map<String, dynamic> srcJson) => _$ChildrenFromJson(srcJson);
Map<String, dynamic> toJson() => _$ChildrenToJson(this);
}
3.在运行打开Terminal 窗口运行命令
flutter packages pub run build_runner build
4.等待运行成功后会自动帮你新建一个刚刚模板代码category_mode.g.dart 的category_mode.g.dart文件
使用实例:
final data = <Categories>[];
Future<void> call() => get(Uri.parse(ServiceUrl.category)).then((value) {
Map<String, dynamic> dataMap = json.decode(value.body);
var bean = CategoryBean.fromJson(dataMap);
data.addAll(bean.categories);
});
|