Skip to content

Conversation

@RossComputerGuy
Copy link

@RossComputerGuy RossComputerGuy commented Jun 13, 2025

This is useful for disposing data which was created in a future provider.

Summary by CodeRabbit

  • New Features
    • Added an optional parameter to support custom disposal logic in the FutureProvider widget, enabling better resource cleanup when the provider is removed.

@coderabbitai
Copy link

coderabbitai bot commented Jun 13, 2025

Walkthrough

The FutureProvider constructor in the async provider library was updated to accept an optional dispose parameter, which is forwarded to the superclass DeferredInheritedProvider. The disposal logic in DeferredInheritedProvider was modified to handle disposal differently when the provided type is a Future, deferring disposal until the future completes. No other logic or control flow changes were made.

Changes

File(s) Change Summary
packages/provider/lib/src/async_provider.dart Added optional dispose parameter to FutureProvider constructor and passed it to superclass.
packages/provider/lib/src/deferred_inherited_provider.dart Changed dispose parameter and field type from Dispose<T>? to Dispose<R>?; modified disposal logic to defer disposal until future completes when T is Future<R>.

Poem

A tweak to how providers close,
Now dispose can guide the flows.
With care, async dreams unwind,
As rabbits code and futures bind.
A gentle hop, a tidy end—
To every future, now a friend! 🐇✨


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/provider/lib/src/async_provider.dart (1)

184-194: Add doc comment for the new dispose parameter

dispose is now part of the public API, but the constructor header comment above (lines 181-184) hasn’t been updated to explain its purpose or usage contract (e.g. when it is called, whether it can be async, etc.). This can confuse consumers scanning the source or relying on generated docs.

 /// Creates a [Future] from `create` and subscribes to it.
 ///
-/// `create` must not be `null`.
+/// `create` must not be `null`.
+///
+/// The optional [dispose] callback is invoked with the last exposed value
+/// when the provider is removed from the widget tree, allowing cleanup of
+/// resources (closing streams, cancelling timers, etc.).
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3ee02e4 and 6e7f04b.

📒 Files selected for processing (1)
  • packages/provider/lib/src/async_provider.dart (2 hunks)
🔇 Additional comments (1)
packages/provider/lib/src/async_provider.dart (1)

195-200: Forwarding dispose to super looks correct

Passing the parameter straight through to DeferredInheritedProvider ensures the disposal logic is wired without altering existing behaviour—good change.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
packages/provider/lib/src/deferred_inherited_provider.dart (1)

160-169: 🛠️ Refactor suggestion

Delegate stores the new dispose type – same compatibility concern

final Dispose<R>? dispose; propagates the issue mentioned above to the delegate.
If you keep the current design, update the documentation of all providers (and their tests) to reflect that dispose now receives the value instead of the controller.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e7f04b and ea68b95.

📒 Files selected for processing (2)
  • packages/provider/lib/src/async_provider.dart (2 hunks)
  • packages/provider/lib/src/deferred_inherited_provider.dart (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/provider/lib/src/async_provider.dart
🔇 Additional comments (1)
packages/provider/lib/src/deferred_inherited_provider.dart (1)

35-44: Switching dispose from Dispose<T>Dispose<R> is a breaking change – double-check all call-sites

DeferredInheritedProvider is reused by StreamProvider, ChangeNotifierProxyProvider, … etc.
Those providers currently pass a callback that expects the controller (T) rather than the exposed value (R).
Changing the type here silently breaks those call-sites and will surface as an Invalid cast or a compile-time error once NNBD-strict is enabled.

Please audit every constructor that forwards dispose: to this class and make sure their generic argument now matches the new contract, or consider keeping the original signature and introducing a separate parameter (e.g. disposeValue) for the future-specific path.

Comment on lines 221 to +229
super.dispose();
if (_didBuild) {
delegate.dispose?.call(element!, _controller as T);
if (T is Future<R>) {
(_controller as Future<R>).then((value) => delegate.dispose?.call(element!, value));
} else if (isLoaded) {
delegate.dispose?.call(element!, value);
} else {
delegate.dispose?.call(element!, _controller as R);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Compile-time error & wrong cast inside _CreateDeferredInheritedProviderElement.dispose

  1. if (T is Future<R>) is invalid Dart – the left-hand side of is must be an expression, not a type parameter.
  2. delegate.dispose?.call(element!, _controller as R); will throw at runtime when TR (e.g. StreamProvider<Stream<int>, int>), because _controller is a Stream<int> while R is int.

Suggested fix:

-      if (T is Future<R>) {
-        (_controller as Future<R>).then((value) => delegate.dispose?.call(element!, value));
+      if (_controller is Future<R>) {
+        // FutureProvider – dispose after the Future completes.
+        (_controller as Future<R>).then(
+          (resolved) => delegate.dispose?.call(element!, resolved),
+          onError: (_) {}, // ignore errors, we cannot dispose a failed value
+        );
       } else if (isLoaded) {
         delegate.dispose?.call(element!, value);
       } else {
-        delegate.dispose?.call(element!, _controller as R);
+        // No value produced; fall back to disposing the controller itself.
+        // Cast to `dynamic` to avoid a bad runtime cast when T ≠ R.
+        delegate.dispose?.call(element!, _controller as dynamic);
       }

This eliminates the compile error and prevents a potential TypeError at runtime.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
super.dispose();
if (_didBuild) {
delegate.dispose?.call(element!, _controller as T);
if (T is Future<R>) {
(_controller as Future<R>).then((value) => delegate.dispose?.call(element!, value));
} else if (isLoaded) {
delegate.dispose?.call(element!, value);
} else {
delegate.dispose?.call(element!, _controller as R);
}
super.dispose();
if (_didBuild) {
if (_controller is Future<R>) {
// FutureProvider – dispose after the Future completes.
(_controller as Future<R>).then(
(resolved) => delegate.dispose?.call(element!, resolved),
onError: (_) {}, // ignore errors, we cannot dispose a failed value
);
} else if (isLoaded) {
delegate.dispose?.call(element!, value);
} else {
// No value produced; fall back to disposing the controller itself.
// Cast to `dynamic` to avoid a bad runtime cast when T ≠ R.
delegate.dispose?.call(element!, _controller as dynamic);
}
🤖 Prompt for AI Agents
In packages/provider/lib/src/deferred_inherited_provider.dart around lines 221
to 229, the code incorrectly uses a type check with a type parameter in `if (T
is Future<R>)`, which is invalid in Dart, and performs an unsafe cast
`_controller as R` that can cause runtime errors when T and R differ. To fix
this, replace the invalid type check with a runtime type check on the actual
instance held by _controller, such as using `_controller is Future<R>`, and
avoid casting _controller directly to R; instead, ensure the correct value is
passed to delegate.dispose by handling each case based on the runtime type of
_controller or by restructuring the logic to safely extract the value without
unsafe casts.

Key? key,
required Create<Future<T>?> create,
required T initialData,
Dispose<T>? dispose,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is impractical because more often than not, it's not T that needs disposing when using futures/streams. It's something else, like a Completer/StreamController/...

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, the problem I was running into was that if it were a Future then I didn't have access to the data since it was already completed. How would I get around this to work for Completer or a StreamController?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's no easy solution with the API that Provider offers. We'd have to make a breaking change and do:

StreamProvider(create: (context, ref) {
  final controller = StreamController()
  ref.onDispose(() => controller.close());
  return controller.stream;
})

That's the API Riverpod uses.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants