搜尋套件、儲存庫與 APP 分類

套件詳情v0.3.0

riverpod_context

此套件為 riverpod 恢復了 context.read 和 context.watch 功能

AndroidiOSWebmacOSWindowsLinux
近 30 天下載
345
喜歡數
18
Pub 分數
150

安裝套件

flutter pub add riverpod_context

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

riverpod_context 套件恢復了 Riverpod 中被較新版本移除的便利 context.read 與 context.watch 方法。它讓開發者能直接從 BuildContext 存取 providers,無需使用較冗長的 ProviderContainer 或其他變通方式。這在跨多個平台使用 Riverpod 的狀態管理系統時,提升了程式碼可讀性與開發者體驗。

適用情境

  • 在小部件中訪問提供者
  • 簡化UI中的狀態使用
  • 在複雜的組件樹中提升程式碼清晰度
  • 在非 ProviderContainer 環境中啟用 watch 和 read 模式
  • 使用 RiverPod 時減少樣板程式碼

主要特色

  • 重新引入 context.read()
  • 重新引入 context.watch()
  • 與所有 Riverpod 提供者相容
  • 支援所有主要平台
  • 所需的設定最少

適合對象

  • 使用 Riverpod 的開發者若懷念 context.read/watch
  • 需要乾淨、可讀的狀態存取的專案
  • 重視開發者體驗的團隊
  • 針對多個平台的應用程式
  • 使用大量狀態管理的Flutter應用

使用建議

  • 需要謹慎使用,以避免效能問題
  • 如果直接使用 ProviderContainer,則不需要
  • 可能與未來的 Riverpod 更新衝突
  • 最好與適當的提供者範圍結合使用
  • 避免在深度嵌套或頻繁重建的組件中使用

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

This package brings back the context extensions for riverpod that were discontinued in version 1.0.0.

  • To read any provider, do context.read(myProvider)
  • To watch any provider, do context.watch(myProvider)

This package is meant to be used alongside riverpod and offers an alternative to the official ConsumerWidget and ConsumerStatefulWidget.

Getting Started

This assumes you already have flutter_riverpod (or hooks_riverpod) set up.

First, add riverpod_context as a dependency.

flutter pub add riverpod_context

Next, add InheritedConsumer underneath the root ProviderScope:

// Before
ProviderScope(
  child: MyApp(),
)
// After
ProviderScope(
  child: InheritedConsumer(
    child: MyApp(),
  ),
)

That's all.

Context Extensions

riverpod_context provides four convenient context extensions to interact with your providers.

context.read

context.read can be used anywhere without any special consideration. It naturally supports any providers, provider families as well as the new .select() syntax.

Widget build(BuildContext context) {
  // this won't rebuild based on 'myValue'
  String myValue = context.read(myProvider);
  return Text(myValue);
}
context.watch

context.watch watches the provider and triggers a rebuild of the given context when the providers state changes. It again supports any providers, provider families as well as the new .select() syntax.

Widget build(BuildContext context) {
  // this will rebuild each time 'myValue' changes
  String myValue = context.watch(myProvider);
  return Text(myValue);
}

🚨 There are a few important considerations to make when using context.watch. With those, you can also safely use any .autoDispose providers.

1. Only use inside build()

context.watch can only be used inside the build() method of a widget. Especially interaction callbacks (like onPressed) and StatefulWidgets initState, didChangeDependencies and other lifecycle handlers are not allowed.

2. Be cautious when conditionally watching providers

It is possible to conditionally watch providers. This is the case when context.watch may not be called on every rebuild.

Widget build(BuildContext context) {
  if (myCondition) {
    return Text(context.watch(myProvider));
  } else {
    return Container();
  }
}

In this example, when myCondition is false, context.watch is not called. This leads to an issue where the dependencies of the provider are not clearly defined.

It is important to make sure that this does not happen, since it can lead to leaking memory and wrong behavior!

Preventing this is however pretty simple.

If there exists another context.watch on the same context, this issue is resolved. Generally speaking, it requires at least one context.watch call on every build to be safe.

If in the example above, the myCondition actually comes from another context.watch call, you are safe.

Widget build(BuildContext context) {
  if (context.watch(myConditionProvider)) {
    // don't worry about this being called conditionally, 
    // we already have called context.watch once before
    return Text(context.watch(myProvider));
  } else {
    return Container();
  }
}

If not, use context.prime().

3. Or use context.prime() when conditionally watching providers

If context.watch is - under certain conditions - not called on every rebuild, you have to "prime" the context for the missing provider. This can be done using a simple context.prime() call.

In the previous example, this can be placed either in the else, or unconditionally at the top. It also has no effect to do it multiple times.

Widget build(BuildContext context) {
  context.prime(); // option 1: always prime
  if (myCondition) {
    return Text(context.watch(myProvider));
  } else {
    context.prime(); // option 2: prime to account for missing context.watch call
    return Container();
  }
}

As a rule just remember this:

Wherever you use context.watch conditionally, make sure to either have another unconditional context.watch or use context.prime on the same context.

Or in other words:

You are safe if on each rebuild there always is at least one call to either context.watch or context.prime.

context.refresh

context.refresh refreshes any provider.

Widget build(BuildContext context) {
  return TextButton(
    onPressed: () {
      context.refresh(myProvider);
    },
    child: const Text('Refresh'),
  );
}
context.invalidate

context.invalidate invalidates any provider.

Widget build(BuildContext context) {
  return TextButton(
    onPressed: () {
      context.invalidate(myProvider);
    },
    child: const Text('Invalidate'),
  );
}
context.listen

context.listen Listens to a provider without triggering a rebuild. This can be used inside the build() method or in the didChangeDependencies() of a stateful widget.

Widget build(BuildContext context) {
  
  context.listen(myProvider, (previous, value) {
    // do something
  });
  
  return SomeWidget();
}
Idempotent listeners

There will only ever be a single active listener for a specific context, meaning that calling context.listen multiple times for the same provider will only have the last listener active. Only because of this it is safe to use context.listen inside the build() method across rebuilds.

You can set fireImmediate: true to immediately fire the listener once. This will be ignored when re-listening to a provider, i.e. after a rebuild.

Widget build(BuildContext context) {

  // across multiple rebuilds, there will only exist a single listener on this provider
  // only on the first build, the listener will fire immediately
  context.listen(myProvider, (previous, value) {
    // do something
  }, fireImmediately: true);
  
  return SomeWidget();
}
Closing listeners

All listeners will only be closed when the context is disposed. Therefore it has no effect to call context.listen conditionally, especially with .autoDispose providers.

There are two ways to control the closing of a listener:

  • By using context.unlisten you can close the active listener on a provider.
  • When wanting more control over a listener, use context.subscribe.
Widget build(BuildContext context) {

  if (myCondition) {
    context.listen(myProvider, (previous, value) {
      // do something
    });
  } else {
    // this will remove the active listener on this provider
    // and properly dispose an .autoDispose provider
    context.unlisten(myProvider);
  }
  
  return SomeWidget();
}
context.subscribe

context.subscribe listens to a provider and returns the ProviderSubscription. Use this when you need to manually manage the subscription of a provider.

  • This can be used wherever you have a BuildContext, even in the initState() method.
  • Make sure to call subscription.close() when the listener is no longer needed.
class MyWidgetState extends State<MyWidget> {
  
  late ProviderSubscription subscription;
  
  @override
  void initState() {
    // store the returned subscription in a variable
    subscription = context.subscribe(myProvider, (previous, value) {
      // do something
    });
  }
  
  // ...
  
  @override dispose() {
    // make sure to properly close the subscription
    subscription.close();
  }
}

所屬分類

依賴

依賴清單 1 項

原始碼儲存庫

使用此套件的專案

暫無相關資料。