You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Riverpod中创建抽象/基础Notifier类以复用逻辑?

解决方案:基于公开的AsyncNotifier抽象公共逻辑

1. 定义抽象基类(核心复用逻辑)

创建继承自AsyncNotifier的抽象基类,封装搜索、状态管理等公共逻辑,仅将差异化的API调用定义为抽象方法:

import 'package:flutter_riverpod/flutter_riverpod.dart';

abstract class SearchNotifierBase<T> extends AsyncNotifier<List<T>> {
  // 抽象方法:由子类实现具体API调用
  Future<List<T>> fetchSearchResults(String query);

  // 公共搜索逻辑:统一处理加载、成功、错误状态
  Future<void> search(String query) async {
    state = const AsyncValue.loading();
    try {
      final results = await fetchSearchResults(query);
      state = AsyncValue.data(results);
    } catch (e, stackTrace) {
      state = AsyncValue.error(e, stackTrace);
    }
  }

  // 按需添加其他公共逻辑,比如重置状态
  void resetState() {
    state = const AsyncValue.data([]);
  }
}

2. 实现具体Notifier子类

每个具体Notifier只需继承基类,实现fetchSearchResults方法,专注于自身的API调用即可:

MyNotifierOne

class MyNotifierOne extends SearchNotifierBase<ItemOne> {
  @override
  Future<List<ItemOne>> fetchSearchResults(String query) async {
    // 调用对应API接口
    return await ApiServiceOne.searchItems(query);
  }
}

// 对应Provider
final myNotifierOneProvider = AsyncNotifierProvider<MyNotifierOne, List<ItemOne>>(
  () => MyNotifierOne(),
);

MyNotifierTwo

class MyNotifierTwo extends SearchNotifierBase<ItemTwo> {
  @override
  Future<List<ItemTwo>> fetchSearchResults(String query) async {
    return await ApiServiceTwo.searchItems(query);
  }
}

final myNotifierTwoProvider = AsyncNotifierProvider<MyNotifierTwo, List<ItemTwo>>(
  () => MyNotifierTwo(),
);

3. 扩展:用mixin复用逻辑(可选)

若不想用基类继承,可通过mixin实现逻辑复用(需让具体Notifier继承AsyncNotifier并混入mixin):

mixin SearchMixin<T> on AsyncNotifier<List<T>> {
  Future<List<T>> fetchSearchResults(String query);

  Future<void> search(String query) async {
    state = const AsyncValue.loading();
    try {
      final results = await fetchSearchResults(query);
      state = AsyncValue.data(results);
    } catch (e, stackTrace) {
      state = AsyncValue.error(e, stackTrace);
    }
  }
}

// 使用方式
class MyNotifierThree extends AsyncNotifier<List<ItemThree>> with SearchMixin<ItemThree> {
  @override
  Future<List<ItemThree>> fetchSearchResults(String query) async {
    return await ApiServiceThree.searchItems(query);
  }
}

final myNotifierThreeProvider = AsyncNotifierProvider<MyNotifierThree, List<ItemThree>>(
  () => MyNotifierThree(),
);

关键说明

  • 避开内部类限制:直接基于公开的AsyncNotifier抽象,完全符合Riverpod公开API规范,无内部类访问问题。
  • 泛型适配:通过泛型T兼容不同搜索结果类型,保证基类/mixin的通用性。
  • 职责分离:公共逻辑统一维护,子类仅需实现差异化API,大幅提升代码复用性与可维护性。

内容的提问来源于stack exchange,提问作者Burhanuddin Rashid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 23:31:03