跳到主要内容

状态管理(Riverpod)

Riverpod 与 ViewModel / Notifier 约定

角色

概念用法
Provider无状态依赖(Repository、配置)
Notifier / AsyncNotifier页面或会话状态
ref.watchbuild / 依赖图订阅
ref.read回调里发动作、读一次性
ref.listen副作用(导航、SnackBar)

页面级 Notifier 建议 autoDispose,离开路由释放。

SnackBar:在 ref.listen / 回调里用 showAppSnackBarText(context, …)(shared/presentation/widgets/app_snackbar.dart),避免 dialog / root 导航下被挡住。

模式

  1. domain 定义接口与实体
  2. data 实现仓储
  3. presentation 的 Notifier 调仓储,暴露不可变 State
  4. Widget 只 watch 状态、调用 Notifier 方法

示例类名以仓库为准;下面仅为结构示意:

@immutable
class ExampleState {
  const ExampleState({this.loading = false});
  final bool loading;
  ExampleState copyWith({bool? loading}) =>
      ExampleState(loading: loading ?? this.loading);
}

class ExampleNotifier extends Notifier<ExampleState> {
  @override
  ExampleState build() => const ExampleState();

  Future<void> load() async {
    state = state.copyWith(loading: true);
    // await repo...
    state = state.copyWith(loading: false);
  }
}

与认证 / API

  • luotopiaAuthProvider 管登录态
  • dioProvider watch token 与 customServerUrl

见 认证 · API 对接。

相关