Flutter枚举与密封类代码生成插件super_enum_sealed_generators的使用

Flutter枚举与密封类代码生成插件super_enum_sealed_generators的使用

在Flutter开发中,使用密封类(sealed classes)可以有效管理状态或结果类型。super_enum_sealed_generators 是一个强大的插件,用于自动生成密封类及其相关方法,帮助开发者更高效地处理复杂的状态逻辑。


特性

  • 自动生成密封类及其子类。
  • 提供静态工厂方法,例如 Result.success(data: 0)
  • 支持多种匹配方法,如 when, whenOrElse, whenOrDefault 等。
  • 支持数据类的相等性和哈希值生成。
  • 支持泛型和空安全。
  • 自动生成 toString() 方法。
  • 支持自动解包和继承。

使用步骤

1. 添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  sealed_annotations: ^latest.version

dev_dependencies:
  sealed_generators: ^latest.version

运行 flutter pub get 安装依赖。


2. 创建密封类定义文件

创建一个文件(例如 weather.sealed.dart),并定义密封类结构:

import 'package:sealed_annotations/sealed_annotations.dart';

part 'weather.sealed.dart'; // 指定生成的目标文件

@Sealed()
abstract class _Weather {
  void sunny(); // 定义抽象方法
  void rainy(int rain); // 带参数的方法
  void windy(double velocity, double? angle); // 带可选参数的方法
}

3. 运行代码生成器

在项目根目录下运行以下命令生成密封类代码:

dart run build_runner build

4. 查看生成的代码

运行生成器后,会在指定的 part 文件中生成密封类及其子类代码。以下是生成代码的简化版本:

abstract class Weather {
  const factory Weather.sunny() = WeatherSunny;
  const factory Weather.rainy({required int rain}) = WeatherRainy;
  const factory Weather.windy({required double velocity, double? angle}) = WeatherWindy;

  bool isSunny() => this is WeatherSunny;
  bool isRainy() => this is WeatherRainy;
  bool isWindy() => this is WeatherWindy;

  R when<R extends Object?>({
    required R Function(WeatherSunny sunny) sunny,
    required R Function(WeatherRainy rainy) rainy,
    required R Function(WeatherWindy windy) windy,
  }) {
    if (this is WeatherSunny) {
      return sunny(this as WeatherSunny);
    } else if (this is WeatherRainy) {
      return rainy(this as WeatherRainy);
    } else if (this is WeatherWindy) {
      return windy(this as WeatherWindy);
    }
    throw Exception('Unhandled case');
  }

  // 其他方法类似 ...
}

class WeatherSunny extends Weather {
  @override
  String toString() => 'Weather.sunny()';
}

class WeatherRainy extends Weather {
  WeatherRainy({required this.rain});

  final int rain;

  @override
  String toString() => 'Weather.rainy(rain: $rain)';
}

class WeatherWindy extends Weather {
  WeatherWindy({required this.velocity, this.angle});

  final double velocity;
  final double? angle;

  @override
  String toString() => 'Weather.windy(velocity: $velocity, angle: $angle)';
}

5. 使用生成的密封类

在实际代码中,您可以使用生成的密封类来管理状态。以下是一个完整的示例:

文件 result.dart

import 'package:sealed_annotations/sealed_annotations.dart';

part 'result.sealed.dart';

@Sealed()
abstract class _Result<D extends Object> {
  void success(D data);
  void error(Object exception);
}

文件 weather.dart

import 'package:sealed_annotations/sealed_annotations.dart';

part 'weather.sealed.dart';

@Sealed()
abstract class _Weather {
  void sunny();
  void rainy(int rain);
  void windy(double velocity, double? angle);
}

文件 main.dart

import 'result.dart';
import 'weather.dart';

void main() {
  // 使用Weather密封类
  final a = Weather.sunny();
  final b = Weather.rainy(rain: 12);
  final c = Weather.windy(velocity: 1.5, angle: null);

  print(a); // 输出: Weather.sunny()
  print(b); // 输出: Weather.rainy(rain: 12)
  print(c); // 输出: Weather.windy(velocity: 1.5, angle: null)

  // 使用Result密封类
  final d = Result.success(data: 1);
  final e = Result.success(data: 5.6);
  final f = Result.error(exception: 'error');

  print(d); // 输出: Result.success(data: 1)
  print(e); // 输出: Result.success(data: 5.6)
  print(f); // 输出: Result.error(exception: error)
}

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

1 回复

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


super_enum_sealed_generators 是一个用于 Flutter 的代码生成插件,它可以帮助你生成枚举和密封类的相关代码,从而减少样板代码的编写,提高开发效率。以下是如何使用 super_enum_sealed_generators 插件的详细步骤。

1. 添加依赖

首先,在你的 pubspec.yaml 文件中添加 super_enum_sealed_generatorsbuild_runner 依赖:

dependencies:
  flutter:
    sdk: flutter
  super_enum_sealed: ^1.0.0  # 请使用最新版本

dev_dependencies:
  build_runner: ^2.1.0  # 请使用最新版本
  super_enum_sealed_generators: ^1.0.0  # 请使用最新版本

2. 创建枚举或密封类

在你的 Dart 文件中,定义你的枚举或密封类。例如,我们创建一个 Result 密封类:

import 'package:super_enum_sealed/super_enum_sealed.dart';

@superEnum
sealed class Result<T> {
  factory Result.success(T value) = Success<T>;
  factory Result.failure(String error) = Failure<T>;
}

@superEnum
class Success<T> extends Result<T> {
  final T value;
  Success(this.value);
}

@superEnum
class Failure<T> extends Result<T> {
  final String error;
  Failure(this.error);
}

3. 生成代码

运行以下命令来生成代码:

flutter pub run build_runner build

这将生成一个与你的密封类或枚举相关的 .g.dart 文件,其中包含了自动生成的代码。

4. 使用生成的代码

你可以在你的项目中使用生成的代码。例如,使用 Result 密封类:

void handleResult(Result<int> result) {
  result.when(
    success: (value) => print('Success: $value'),
    failure: (error) => print('Failure: $error'),
  );
}

void main() {
  final result = Result.success(42);
  handleResult(result);  // 输出: Success: 42

  final errorResult = Result.failure('Something went wrong');
  handleResult(errorResult);  // 输出: Failure: Something went wrong
}

5. 其他功能

super_enum_sealed_generators 还支持其他功能,如生成 toString==hashCode 方法,以及生成 copyWith 方法等。你可以通过注解来配置这些功能。

6. 清理生成的文件

如果你想要清理生成的文件,可以运行以下命令:

flutter pub run build_runner clean
回到顶部