Flutter注解处理插件riverfit_annotation的使用

Flutter注解处理插件riverfit_annotation的使用

Riverfit

Riverfit Codecov License

概述

Riverfit 是一个Dart代码生成库,旨在集成 riverpod_generatorretrofit_generator 的功能。

为什么使用Riverfit?

这种集成适用于依赖于Riverpod进行状态管理以及通过Retrofit进行API交互的项目。

当使用 @Riverpod 注解时,可以选择为函数或类添加注解。我更倾向于为类添加注解,尤其是为了更好的组织、可读性和可维护性。

  • 更好的封装性:类将相关的逻辑和数据组合在一起,使理解并管理provider的行为更加容易。
  • 更好的可读性:有了专用的类,可以立即清楚地了解provider代表什么,并且可以添加额外的方法或属性以扩展其功能。
  • 可扩展性:类允许你添加与provider状态直接相关的其他方法、属性或计算值。

然而,目前无法在同一类上使用 riverpod_generatorretrofit_generator 的注解,因为 @Riverpod 期望的是具体类,而 @RestApi 期望的是抽象类。

Riverfit通过分析带有 @Riverfit 注解的类来解决这个问题:

  • 将provider代码生成委托给Riverpod Generator。
  • 生成包含转发调用到Retrofit成员的wrapper方法的provider扩展类。这消除了手动代理样板的需求。

子项目

1. riverfit_annotation

提供了用于标记类以供Riverfit处理的 @Riverfit()/@riverfit 注解。将其用作 @Riverpod()@riverpod 注解的替代品。

使用方法

  1. 创建你的标准Retrofit抽象类作为API合同。
import 'package:dio/dio.dart';
import 'package:retrofit/retrofit.dart';

part 'api.g.dart';

@RestApi(baseUrl: 'https://example.com')
abstract class Api {
  factory Api(Dio dio, {String? baseUrl}) = _Api;

  @GET('/fetchData')
  Future<dynamic> fetchData();

  @PUT('/pushData/{id}')
  Future<dynamic> pushData(String id);
}
  1. 创建一个API客户端作为要提供的类
import 'package:riverfit_annotation/riverfit_annotation.dart';

@Riverfit(keepAlive: true, dependencies: [OtherProvider])
class ApiClient extends _$ApiClient {
  // 声明一个Retrofit成员
  late final Api _api;

  @override
  Future<ApiClient> build() async {
    // 初始化逻辑在这里...
    // 例如自定义Dio配置或添加跨切关注点(如日志记录或身份验证)的拦截器
    _api = Api(Dio());
    return this;
  }
}

如果使用AutoDisposeProvider(keepAlive: false)

import 'package:riverfit_annotation/riverfit_annotation.dart';

@riverfit
class ApiClient extends _$ApiClient {
  // 声明一个Retrofit成员
  late final Api _api;

  @override
  Future<ApiClient> build() async {
    // 初始化逻辑在这里...
    // 例如自定义Dio配置或添加跨切关注点(如日志记录或身份验证)的拦截器
    _api = Api(Dio());
    return this;
  }
}
  1. 生成代码
dart run build_runner build --delete-conflicting-outputs

实现细节

注解将所有参数代理给Riverpod注解,目前包括:

  • keepAlive: 是否即使在provider不再使用时也要保持其状态。默认为 false
  • dependencies: 该类所依赖的Riverpod provider列表。

2. riverfit_generator

这是将Riverpod和Retrofit代码生成统一的核心生成器。它确保注解被正确处理并生成provider和扩展方法。

特性

  • 为带注解的类生成Riverpod provider代码。
  • 创建无缝调用Retrofit成员的wrapper方法。

示例

运行 dart run build_runner build,生成的代码将包括:

  1. ApiClient 的Riverpod provider。
  2. RestApi 成员 Api 的wrapper方法的扩展类。

生成输出:

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'api_client.dart';

// Riverpod provider (a pass-through to riverpod_generator.generate())
String _$apiClientHash() => r'XXXX';

/// See also [ApiClient].
@ProviderFor(ApiClient)
final apiClientProvider = AsyncNotifierProvider<ApiClient, ApiClient>.internal(
  ApiClient.new,
  name: r'apiClientProvider',
  debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$apiClientHash,
  dependencies: null,
  allTransitiveDependencies: null,
);

typedef _$ApiClient = AsyncNotifier<ApiClient>;

// Wrapper methods for Retrofit member
extension ApiClientExtension on ApiClient {
  Future<String> fetchData() {
    return _api.fetchData();
  }

  Future<void> pushData(int id) {
    return _api.pushData(id);
  }
}

安装

在你的 pubspec.yaml 中添加以下依赖项:

dependencies:
  riverfit_annotation: ^1.0.0

dev_dependencies:
  riverfit_generator: ^1.0.0
  build_runner: ^2.4.0

更多关于Flutter注解处理插件riverfit_annotation的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter注解处理插件riverfit_annotation的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


riverfit_annotation 是一个用于 Flutter 的注解处理插件,通常与 riverpod 状态管理库结合使用,以简化代码生成和提高开发效率。以下是如何使用 riverfit_annotation 插件的基本步骤:

1. 添加依赖

首先,在你的 pubspec.yaml 文件中添加 riverfit_annotationbuild_runner 作为依赖项。

dependencies:
  flutter:
    sdk: flutter
  riverpod: ^2.0.0
  riverfit_annotation: ^1.0.0

dev_dependencies:
  build_runner: ^2.0.0

2. 创建注解类

使用 riverfit_annotation 提供的注解来标记你的类或方法。例如,你可以使用 @RiverfitProvider 注解来生成 Provider

import 'package:riverfit_annotation/riverfit_annotation.dart';

part 'example.g.dart';

@RiverfitProvider()
class ExampleProvider {
  String getMessage() => "Hello, Riverfit!";
}

3. 生成代码

运行 build_runner 来生成代码。在终端中执行以下命令:

flutter pub run build_runner build

这将生成一个名为 example.g.dart 的文件,其中包含 ExampleProviderProvider 实现。

4. 使用生成的代码

在生成的代码中,你可以直接使用生成的 Provider

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'example.dart';

final exampleProvider = Provider<ExampleProvider>((ref) {
  return ExampleProvider();
});

void main() {
  runApp(ProviderScope(
    child: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Riverfit Example'),
        ),
        body: Consumer(
          builder: (context, watch, child) {
            final example = watch(exampleProvider);
            return Center(
              child: Text(example.getMessage()),
            );
          },
        ),
      ),
    );
  }
}

5. 自定义注解

riverfit_annotation 提供了多种注解,你可以根据需要选择和使用。例如,@RiverfitStateNotifier 用于生成 StateNotifier@RiverfitFutureProvider 用于生成 FutureProvider 等。

6. 清理生成的文件

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

flutter pub run build_runner clean
回到顶部