Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add dispose to FutureProvider#912

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
RossComputerGuy wants to merge1 commit intorrousselGit:master
base:master
Choose a base branch
Loading
fromRossComputerGuy:feat/future-dispose

Conversation

@RossComputerGuy
Copy link

@RossComputerGuyRossComputerGuy commentedJun 13, 2025
edited by coderabbitaibot
Loading

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

coderabbitaibot commentedJun 13, 2025
edited
Loading

Walkthrough

TheFutureProvider constructor in the async provider library was updated to accept an optionaldispose parameter, which is forwarded to the superclassDeferredInheritedProvider. The disposal logic inDeferredInheritedProvider was modified to handle disposal differently when the provided type is aFuture, 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.dartAdded optionaldispose parameter toFutureProvider constructor and passed it to superclass.
packages/provider/lib/src/deferred_inherited_provider.dartChangeddispose parameter and field type fromDispose<T>? toDispose<R>?; modified disposal logic to defer disposal until future completes whenT isFuture<R>.

Poem

A tweak to how providers close,
Nowdispose 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 withCodeRabbit:

  • 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 oursupport 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 togenerate 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 theconfiguration 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 ourDocumentation for detailed information on how to use CodeRabbit.
  • Join ourDiscord Community to get help, request features, and share feedback.
  • Follow us onX/Twitter for updates and announcements.

Copy link

@coderabbitaicoderabbitaibot 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 newdispose 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 between3ee02e4 and6e7f04b.

📒 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:Forwardingdispose to super looks correct

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

Copy link

@coderabbitaicoderabbitaibot 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 newdispose 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 thatdispose now receivesthe value instead ofthe controller.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between6e7f04b andea68b95.

📒 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:Switchingdispose fromDispose<T>Dispose<R> is a breaking change – double-check all call-sites

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

Please audit every constructor that forwardsdispose: 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!, _controllerasT);
if (TisFuture<R>) {
(_controllerasFuture<R>).then((value)=> delegate.dispose?.call(element!, value));
}elseif (isLoaded) {
delegate.dispose?.call(element!, value);
}else {
delegate.dispose?.call(element!, _controllerasR);
}

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 ofis must bean expression, not a type parameter.
  2. delegate.dispose?.call(element!, _controller as R); will throw at runtime whenTR (e.g.StreamProvider<Stream<int>, int>), because_controller is aStream<int> whileR isint.

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 potentialTypeError 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!, _controllerasT);
if (TisFuture<R>) {
(_controllerasFuture<R>).then((value)=> delegate.dispose?.call(element!, value));
}elseif (isLoaded) {
delegate.dispose?.call(element!, value);
}else {
delegate.dispose?.call(element!, _controllerasR);
}
super.dispose();
if (_didBuild) {
if (_controllerisFuture<R>) {
// FutureProvider – dispose after the Future completes.
(_controllerasFuture<R>).then(
(resolved)=> delegate.dispose?.call(element!, resolved),
onError: (_) {},// ignore errors, we cannot dispose a failed value
);
}elseif (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!, _controllerasdynamic);
}
🤖 Prompt for AI Agents
In packages/provider/lib/src/deferred_inherited_provider.dart around lines 221to 229, the code incorrectly uses a type check with a type parameter in `if (Tis 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 fixthis, replace the invalid type check with a runtime type check on the actualinstance held by _controller, such as using `_controller is Future<R>`, andavoid casting _controller directly to R; instead, ensure the correct value ispassed to delegate.dispose by handling each case based on the runtime type of_controller or by restructuring the logic to safely extract the value withoutunsafe casts.

Key? key,
requiredCreate<Future<T>?> create,
requiredT initialData,
Dispose<T>? dispose,

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 notT that needs disposing when using futures/streams. It's something else, like a Completer/StreamController/...

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 aFuture then I didn't have access to the data since it was already completed. How would I get around this to work forCompleter or aStreamController?

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 freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

@rrousselGitrrousselGitrrousselGit left review comments

@coderabbitaicoderabbitai[bot]coderabbitai[bot] left review comments

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

2 participants

@RossComputerGuy@rrousselGit

[8]ページ先頭

©2009-2025 Movatter.jp