riverpod-eager-initialization

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Riverpod — Eager initialization

Riverpod — 预初始化

Instructions

操作说明

Providers are lazy by default: they initialize on first use. There is no built-in "eager" flag (for tree-shaking). To force early initialization, watch the provider at the root of your app so it stays alive and runs immediately.
Providers默认是懒加载的:它们在首次使用时才初始化。目前没有内置的「预加载」标志(出于摇树优化的考虑)。要强制提前初始化,需在应用的根节点监听该provider,使其保持活跃并立即运行。

Approach

实现方法

Place a Consumer (or ConsumerWidget) directly under ProviderScope that only watches the providers you want to initialize and returns your real app as child:
dart
void main() {
  runApp(ProviderScope(child: MyApp()));
}

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return const _EagerInitialization(child: MaterialApp());
  }
}

class _EagerInitialization extends ConsumerWidget {
  const _EagerInitialization({required this.child});
  final Widget child;

  
  Widget build(BuildContext context, WidgetRef ref) {
    ref.watch(myProvider);  // Eagerly initialize
    return child;
  }
}
Only the initializer widget rebuilds when the provider changes; child is unchanged so Flutter does not rebuild the rest of the tree unless something else is listening.
Consumer(或ConsumerWidget)直接放在ProviderScope下方,仅监听你想要初始化的providers,并将实际应用作为child返回:
dart
void main() {
  runApp(ProviderScope(child: MyApp()));
}

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return const _EagerInitialization(child: MaterialApp());
  }
}

class _EagerInitialization extends ConsumerWidget {
  const _EagerInitialization({required this.child});
  final Widget child;

  
  Widget build(BuildContext context, WidgetRef ref) {
    ref.watch(myProvider);  // Eagerly initialize
    return child;
  }
}
只有初始化器widget会在provider变化时重建;child保持不变,因此除非有其他监听,否则Flutter不会重建其余组件树。

Async: loading and error

异步处理:加载与错误

If the provider is async, handle loading/error in the initializer (e.g. show CircularProgressIndicator or error until ready, then return child). Other widgets can use AsyncValue.requireValue to read the data without pattern matching; if they run before the value is ready, it throws with a clear message.
Put the initializer in a shared widget (e.g. MyApp) so tests can reuse the same setup by using that widget.
如果provider是异步的,需在初始化器中处理加载/错误状态(例如,在就绪前显示CircularProgressIndicator或错误信息,然后返回child)。其他widget可以使用AsyncValue.requireValue读取数据,无需模式匹配;如果它们在值就绪前运行,会抛出清晰的错误信息。
将初始化器放在共享widget(如MyApp)中,这样测试可以通过使用该widget复用相同的设置。