flutter 用json_serializable自动生成实体类

添加依赖

dev_dependencies:
  flutter_test:
    sdk: flutter
 
  build_runner: ^2.0.4
  json_serializable: ^4.1.3

新建文件xxx_bean.dart

import 'package:json_annotation/json_annotation.dart';
 
part 'student_bean.g.dart';//这里需要写上报错先不管 等输入命令生成文件后会自动刷新
@JsonSerializable()
class XXX{
  String? name;
 
  int? age;
 
  XXX({this.name, this.age});


  factory XXX.fromJson(Map json) => _$XXXFromJson(json);
 
  Map toJson() => _$XXXToJson(this);
}

pubspec.yaml路径下命令行输入

#生成命令
flutter packages pub run build_runner build

遇到冲突Conflicting outputs were detected and the build is unable to prompt for permission to 命令行输入下面两行 继续敲上面的生成命令

flutter packages pub run build_runner clean
flutter packages pub run build_runner build --delete-conflicting-outputs

你可能感兴趣的:(flutter 用json_serializable自动生成实体类)