Flutter模型生成插件model_generator的使用
Flutter模型生成插件 model_generator 的使用
model_generator 是一个用于生成 JsonSerializable 模型的Flutter插件。本文将详细介绍如何使用该插件,包括配置、运行命令以及一些高级功能。
插件概述
model_generator 可以帮助你快速生成JSON可序列化的Dart类。通过简单的YAML配置文件,你可以定义模型结构,并自动生成对应的Dart代码。
插件信息
运行插件
要运行 model_generator,可以使用以下命令:
flutter packages run model_generator
如果你需要指定不同的配置文件路径,可以通过 --path 参数来指定:
flutter packages run model_generator --path my_other_model_dir/config.yaml
配置文件
默认情况下,model_generator 会在 model_generator/config.yaml 中查找模型文件。你可以在 pubspec.yaml 文件中通过 config_path 来指定自定义的模型文件位置:
model_generator:
  config_path: my_model_dir/config.yaml
默认设置
默认情况下,所有生成的模型会被写入 /lib/model 目录。你可以通过 base_directory 来指定自定义的基础目录:
model_generator:
  base_directory: custom_models
这会将所有模型写入 /lib/custom_models 目录。
FVM支持
如果你使用 FVM(Flutter Version Management)来管理Flutter版本,可以在 pubspec.yaml 中添加 use_fvm 参数:
model_generator:
  use_fvm: true
自定义生成选项
== 和 hashCode
如果你想在生成的模型中包含 == 和 hashCode 方法,可以在 pubspec.yaml 中启用:
model_generator:
  equals_and_hash_code: true
或者针对特定对象进行覆盖:
UserModel:
  path: webservice/user
  equals_and_hash_code: false
  properties:
    id: int
忽略字段
如果某些字段不需要参与 == 和 hashCode 方法的生成,可以使用 ignore_equality: true 标记这些字段:
UserModel:
  path: webservice/user
  equals_and_hash_code: false
  properties:
    id:
      type: int
      ignore_equality: true
    include: String
显式 toJson 方法
默认情况下,json_serializable 不会为其他 json_serializable 对象或列表、映射生成 toJson 方法。你可以通过以下方式启用此功能:
model_generator:
  explicit_to_json: true
或者针对特定对象进行覆盖:
UserModel:
  path: webservice/user
  explicit_to_json: false
  properties:
    id: int
toString 方法
如果你想在生成的模型中包含 toString 方法,可以在 pubspec.yaml 中启用:
model_generator:
  to_string: true
或者针对特定对象进行覆盖:
UserModel:
  path: webservice/user
  to_string: false
  properties:
    id: int
额外的导入和注解
如果你希望在生成的文件中包含额外的导入语句或在生成的模型类上添加额外的注解,可以在 pubspec.yaml 中指定:
model_generator:
  extra_imports:
    - 'package:flutter/foundation.dart'
  extra_annotations:
    - '@immutable'
或者针对特定对象进行覆盖:
UserModel:
  path: webservice/user
  extra_imports:
  extra_annotations:
    - '@someAnnotation'
  properties:
    id: int
默认值
从版本 5.6.0 开始,支持为属性指定默认值。你可以在属性定义中添加 default_value:
UserModel:
  path: webservice/user
  properties:
    id:
      type: int
      default_value: 1
    name:
      type: String
      default_value: "'an example quoted string'"
泛型支持
如果你想让生成的模型支持泛型,可以启用 generate_for_generics:
model_generator:
  generate_for_generics: true
或者针对特定对象进行覆盖:
UserModel:
  path: webservice/user
  generate_for_generics: true
  converters:
    - DateTimeConverter
  properties:
    id: int
扩展其他模型
如果你想让你的模型扩展其他模型,可以使用 extends:
UserDetails:
  path: webservice/user
  extends: UserModel
  properties:
    name: String
内置类型
以下是一些内置类型的描述符:
string/String
int/integer
bool/boolean
double
date/datetime
dynamic/object/any
array
map
示例配置文件
以下是 model_generator/config.yaml 文件的一个示例:
UserModel:
  path: webservice/user
  converters:
    - DateTimeConverter
  properties:
    id: int
    name: String
    salary: double
    something: dynamic
    isLoggedIn:
      type: bool
      default_value: false
    roles: List<String>
    birthday: date
    addresses: List<Address>
    idToAddress: Map<String, Address>
    securityRole:
      type: String
      jsonKey: securityIndicator
    dynamicField: dynamic
    includeIfNullField:
      include_if_null: false # 如果此字段为空,则不会将其添加到JSON对象中(用于PATCH模型)
      type: String
    ignoreField:
      ignore: false # 此字段将在to和from JSON方法中被忽略
      type: String
    ignoreFieldOnlyInFrom:
      includeFromJson: false # 此字段将在from JSON方法中被忽略
      type: String
    ignoreFieldOnlyInTo:
      includeToJson: false # 此字段将在to JSON方法中被忽略
      type: String
    mutableField:
      non_final: true # 字段不会被标记为final
      type: String
    changedAt:
      type: DateTime
    idToAddressList: Map<String, List<Address>>
Address:
  path: webservice/user # 也可以是 package:... 或者以实际文件名结尾 (.dart)
  properties:
    street: String
# 自定义基础目录
CustomBaseDirectoryObject:
  base_directory: custom_models
  path: webservice
  properties:
    path: String
# 自定义JSON转换器。与模型的converters属性一起使用
DateTimeConverter:
  type: json_converter
  path: converter/
示例项目
以下是一个简单的示例项目,展示了如何使用 model_generator 生成模型并将其集成到Flutter应用中。
示例代码
example/lib/main.dart
import 'package:flutter/material.dart';
import 'package:model_generator_example/app.dart';
Future<void> main() async {
  runApp(MyApp());
}
model_generator/config.yaml
UserModel:
  path: webservice/user
  properties:
    id: int
    name: String
    age: int
    is_active: bool?
    created_at: DateTime
    roles: List<String>
    customProperties: Map<String, Property>?
    customPropertiesList: Map<String, List<Property>>?
生成的 user_model.dart
假设你已经运行了 model_generator,它会根据上述配置生成类似如下的 user_model.dart 文件:
import 'package:json_annotation/json_annotation.dart';
import 'package:model_generator_example/models/address.dart'; // 假设这是生成的地址模型
part 'user_model.g.dart';
[@JsonSerializable](/user/JsonSerializable)()
class UserModel {
  final int id;
  final String name;
  final int age;
  final bool? is_active;
  final DateTime created_at;
  final List<String> roles;
  final Map<String, Property>? customProperties;
  final Map<String, List<Property>>? customPropertiesList;
  UserModel({
    required this.id,
    required this.name,
    required this.age,
    this.is_active,
    required this.created_at,
    required this.roles,
    this.customProperties,
    this.customPropertiesList,
  });
  factory UserModel.fromJson(Map<String, dynamic> json) => _$UserModelFromJson(json);
  Map<String, dynamic> toJson() => _$UserModelToJson(this);
}
更多关于Flutter模型生成插件model_generator的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter模型生成插件model_generator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用model_generator插件来生成模型的示例。model_generator通常用于从JSON数据自动生成Dart模型类,从而简化数据解析过程。
步骤 1: 添加依赖
首先,你需要在pubspec.yaml文件中添加json_serializable和build_runner的依赖,因为model_generator通常依赖于这些包来生成代码。虽然model_generator这个包名并不是官方或广泛使用的,但这里我们假设你指的是使用json_serializable生成模型的方式。
dependencies:
  flutter:
    sdk: flutter
  json_annotation: ^4.3.0  # 确保使用最新版本
dev_dependencies:
  build_runner: ^2.1.4  # 确保使用最新版本
  json_serializable: ^6.1.4  # 确保使用最新版本
步骤 2: 创建JSON数据
假设你有一个user.json文件,内容如下:
{
  "name": "John Doe",
  "email": "john.doe@example.com",
  "age": 30
}
步骤 3: 创建模型类
接下来,创建一个Dart文件(例如user_model.dart),并在其中定义一个模型类。使用@JsonSerializable()注解来标记这个类。
import 'package:json_annotation/json_annotation.dart';
part 'user_model.g.dart';  // 生成的代码将会放在这个文件里
@JsonSerializable()
class User {
  final String name;
  final String email;
  final int age;
  User({required this.name, required this.email, required this.age});
  // 从JSON生成User对象
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  // 将User对象转换为JSON
  Map<String, dynamic> toJson() => _$UserToJson(this);
}
步骤 4: 生成代码
在命令行中,导航到你的Flutter项目根目录,然后运行以下命令来生成代码:
flutter pub run build_runner build
这个命令会读取带有@JsonSerializable()注解的类,并生成相应的fromJson和toJson方法。生成的代码会放在之前指定的part文件中(即user_model.g.dart)。
步骤 5: 使用模型类
现在你可以在你的Flutter应用中使用这个模型类了。例如,从一个网络请求中获取JSON数据并解析为User对象:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'user_model.dart';
void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Model Generator Demo')),
        body: Center(
          child: FutureBuilder<User>(
            future: fetchUser(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                }
                User user = snapshot.data!;
                return Text('Name: ${user.name}\nEmail: ${user.email}\nAge: ${user.age}');
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
        ),
      ),
    );
  }
  Future<User> fetchUser() async {
    // 模拟从网络获取JSON数据
    String jsonString = '''
    {
      "name": "John Doe",
      "email": "john.doe@example.com",
      "age": 30
    }
    ''';
    Map<String, dynamic> jsonMap = jsonDecode(jsonString);
    return User.fromJson(jsonMap);
  }
}
以上代码展示了如何使用model_generator(或json_serializable)插件来自动生成并解析JSON数据。注意,实际开发中你可能需要从网络请求中获取JSON数据,这里为了简化示例,直接使用了硬编码的JSON字符串。
 
        
       
             
             
            

