Flutter代码生成插件mix_generator的使用

Flutter代码生成插件mix_generator的使用

mix_generator 是一个用于在 Mix 包中生成 Spec 和 Dto 类的插件。它通过根据注解类自动生成必要的代码来简化 Spec 和 Dto 类的创建。

安装

要使用 mix_generator,你需要在 pubspec.yaml 文件中添加以下依赖项:

dependencies:
  mix: ^0.0.0
  mix_annotations: ^0.0.0

dev_dependencies:
  build_runner: ^0.0.0
  mix_generator: ^0.0.0

然后运行以下命令以安装这些依赖项:

flutter pub get

使用

MixableSpec

[@MixableSpec](/user/MixableSpec)() 注解用于生成可混合的类。下面是一个示例:

import 'package:mix/mix.dart';
import 'package:mix_annotations/mix_annotations.dart';

part 'my_spec.g.dart';

[@MixableSpec](/user/MixableSpec)()
final class MySpec extends Spec<MySpec> with _$MySpec {
  final String? name;
  final int? age;

  const MySpec({this.name, this.age});
}

选项

  • withCopyWith - 默认为 true,生成 copyWith 方法。
  • withEquality - 默认为 true,生成相等性方法。
  • withLerp - 默认为 true,生成 lerp 方法。
  • skipUtility - 默认为 false,跳过实用类。
  • prefix - 默认为 Spec 类名,为生成的类添加前缀。
MixableDto

@MixableDto() 注解用于生成可混合的 Dto。下面是一个示例:

import 'package:mix/mix.dart';
import 'package:mix_annotations/mix_annotations.dart';

part 'value_dto.g.dart';

@MixableDto()
final class ValueDto<Value> extends Dto<Value> with _$MyDto {
  final String? name;
  final int? age;

  const ValueDto({this.name, this.age});
}

选项

  • mergeLists - 默认为 true,就地合并列表。
  • generateUtility - 默认为 true,生成实用类。
  • generateValueExtension - 默认为 true,生成将 Value 转换为 Dto 的值扩展,通过 toDto() 扩展。
MixableProperty

[@MixableProperty](/user/MixableProperty)() 注解用于指定用于代码生成的可混合属性。下面是一个示例:

import 'package:mix_generator/mix_generator.dart';

[@MixableProperty](/user/MixableProperty)(
  dto: MixableFieldDto(type: BoxConstraintsDto),
  utilities: [
    MixableUtility(
      properties: [
        (path: 'minWidth', alias: 'minWidth'),
        (path: 'maxWidth', alias: 'maxWidth'),
      ],
    ),
  ],
)
final BoxConstraints? constraints;
MixableUtility

@MixableUtility() 注解用于指定用于代码生成的可混合实用工具。下面是一个示例:

import 'package:mix_generator/mix_generator.dart';

[@MixableProperty](/user/MixableProperty)(
  utilities: MixableUtility(
    type: BoxDecoration,
    properties: [
      (path: 'color', alias: 'color'),
      (path: 'border', alias: 'border'),
      (path: 'borderRadius', alias: 'borderRadius'),
    ],
  ),
)
final Decoration? decoration;
代码生成

为了生成你的可混合类和 Dto 的代码,运行以下命令:

flutter pub run build_runner build

示例代码

// ignore_for_file: prefer_relative_imports, avoid-importing-entrypoint-exports, camel_case_types
import 'package:flutter/material.dart';
import 'package:mix/mix.dart';
import 'package:mix_annotations/mix_annotations.dart';

part 'box_spec.g.dart';

const _constraints = MixableUtility(
  type: BoxConstraints,
  properties: [
    (path: 'minWidth', alias: 'minWidth'),
    (path: 'maxWidth', alias: 'maxWidth'),
    (path: 'minHeight', alias: 'minHeight'),
    (path: 'maxHeight', alias: 'maxHeight'),
  ],
);

const _foreground = MixableUtility(type: BoxDecoration);
const _boxDecor = MixableUtility(
  type: BoxDecoration,
  properties: [
    (path: 'color', alias: 'color'),
    (path: 'border', alias: 'border'),
    (path: 'border.directional', alias: 'borderDirectional'),
    (path: 'borderRadius', alias: 'borderRadius'),
    (path: 'borderRadius.directional', alias: 'borderRadiusDirectional'),
    (path: 'gradient', alias: 'gradient'),
    (path: 'gradient.sweep', alias: 'sweepGradient'),
    (path: 'gradient.radial', alias: 'radialGradient'),
    (path: 'gradient.linear', alias: 'linearGradient'),
    (path: 'boxShadows', alias: 'shadows'),
    (path: 'boxShadow', alias: 'shadow'),
    (path: 'elevation', alias: 'elevation'),
  ],
);

const _shapeDecor = MixableUtility(
  alias: 'shapeDecoration',
  type: ShapeDecoration,
);

[@MixableSpec](/user/MixableSpec)()
final class BoxSpec extends Spec<BoxSpec> with _$BoxSpec {
  /// {[@macro](/user/macro) box_spec_of}
  static const of = _$BoxSpec.of;

  static const from = _$BoxSpec.from;

  /// Aligns the child within the box.
  final AlignmentGeometry? alignment;

  /// Adds empty space inside the box.
  final EdgeInsetsGeometry? padding;

  /// Adds empty space around the box.
  final EdgeInsetsGeometry? margin;

  /// Applies additional constraints to the child.
  [@MixableProperty](/user/MixableProperty)(utilities: [_constraints])
  final BoxConstraints? constraints;

  /// Paints a decoration behind the child.
  [@MixableProperty](/user/MixableProperty)(utilities: [_boxDecor, _shapeDecor])
  final Decoration? decoration;

  /// Paints a decoration in front of the child.
  [@MixableProperty](/user/MixableProperty)(utilities: [_foreground])
  final Decoration? foregroundDecoration;

  /// Applies a transformation matrix before painting the box.
  final Matrix4? transform;

  /// Aligns the origin of the coordinate system for the [transform].
  final AlignmentGeometry? transformAlignment;

  /// Defines the clip behavior for the box
  /// when [BoxConstraints] has a negative minimum extent.
  final Clip? clipBehavior;

  /// Specifies the width of the box.
  final double? width;

  /// Specifies the height of the box.
  final double? height;

  const BoxSpec({
    this.alignment,
    this.padding,
    this.margin,
    this.constraints,
    this.decoration,
    this.foregroundDecoration,
    this.transform,
    this.transformAlignment,
    this.clipBehavior,
    this.width,
    this.height,
    super.animated,
  });
}

更多关于Flutter代码生成插件mix_generator的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter代码生成插件mix_generator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


mix_generator 是一个用于 Flutter 的代码生成插件,它可以帮助开发者自动生成 Dart 代码,减少重复劳动,提高开发效率。mix_generator 通常用于生成一些样板代码,如模型类、服务类、Bloc 等。

安装 mix_generator

首先,你需要在 pubspec.yaml 文件中添加 mix_generator 作为开发依赖项:

dev_dependencies:
  mix_generator: ^1.0.0
  build_runner: ^2.1.0

然后运行 flutter pub get 来安装依赖。

使用 mix_generator

mix_generator 通常与 build_runner 一起使用,build_runner 是一个用于执行代码生成任务的工具。

1. 创建一个注解类

首先,你需要创建一个注解类,mix_generator 会根据这个注解类来生成代码。例如,你可以创建一个 @JsonSerializable 注解:

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
  final String name;
  final int age;

  User({required this.name, required this.age});

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

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

2. 生成代码

然后,你可以使用 build_runner 来生成代码。在终端中运行以下命令:

flutter pub run build_runner build

这将会生成 user.g.dart 文件,其中包含 _$UserFromJson_$UserToJson 方法的实现。

自定义生成器

你也可以创建自定义的生成器来生成特定类型的代码。例如,你可以创建一个生成 Bloc 类的生成器。

1. 创建一个生成器类

首先,创建一个生成器类,继承自 Generator

import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';

class BlocGenerator extends Generator {
  @override
  Future<String> generate(LibraryReader library, BuildStep buildStep) async {
    // 这里实现生成逻辑
    return '''
      class MyBloc {
        // Bloc logic
      }
    ''';
  }
}

2. 注册生成器

然后,在 build.yaml 文件中注册生成器:

builders:
  bloc_generator:
    import: "package:my_app/bloc_generator.dart"
    builder_factories: ["blocGenerator"]
    build_extensions: {".dart": [".g.dart"]}
    auto_apply: dependents

3. 运行生成器

最后,运行 build_runner 来生成代码:

flutter pub run build_runner build
回到顶部