[Flutter-34] Flutter Json Model

Flutter Json Model

参考链接:https://examplecode.cn/2019/10/06/flutter-json-serializable/

- 添加依赖:

pubspec.yaml
  
dependencies:
  flutter:
    sdk: flutter
  json_annotation: 4.0.1
  
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter
  json_serializable: 4.1.4
  build_runner: 2.1.0

- 操作步骤

  • 1: Create Model, such as User
    user.dart

  • 2: 定义model, 格式为:

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
  int? id;
  String? name;
  String? address;

  User();

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  Map<String, dynamic> toJson() => _$UserToJson(this);
}

  • 3:在目录下,执行命令:
    flutter pub run build_runner build

  • 4: 然后自动生成user.g.dart 文件 和 里面的所有方法

上一篇:10. 注解


下一篇:Mybatis-plus 分页配置