iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🫧

[Flutter] Investigating why a state watched by ref.watch was unexpectedly disposed

に公開

I heard about an incident from ashdik where a state that was supposed to be watched with ref.watch was disposed of before they knew it. I thought this incident and its reason were important for understanding Riverpod, so I'd like to summarize it in this article.

I will explain how ashdik discovered and solved the problem in actual work, and from there, I will delve deeper into the internal mechanics of why it gets disposed of and whether there are any general points to be careful about when using Riverpod.

I hope this helps in safely utilizing Riverpod's autoDispose. Here is the main text.

The Incident Occurred

First, here is the code that reproduces the incident with minimal code.

/// Provider that manages the counter value
@riverpod
class Counter extends _$Counter {
  @override
  int build() => 0;
  void increment() => state += 1;
}

/// Provider that watches [counterProvider] to fetch data
@riverpod
class Articles extends _$Articles {
  @override
  Future<List<Article>> build() async {
    await Future.delayed(const Duration(milliseconds: 500), () {
      // Simulated data fetching process
    });

    return List.generate(
      ref.watch(counterProvider), 
      (index) => 'article no.$index',
    );
  }
}

There is a counterProvider representing a typical counter at the top, and an articlesProvider that watches it via ref.watch.

articlesProvider performs an asynchronous process (simulating fetching an article list from a database) and then generates the state using the number obtained from ref.watch(counterProvider).

Finally, we define ArticlesPage, which builds the UI using the state generated by articlesProvider, and the sample code is complete.

class ArticlesPage extends ConsumerWidget {
  const ArticlesPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final articles = ref.watch(articlesProvider);
    return Scaffold(
      body: // Widget to build the list screen
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          ref.read(counterProvider.notifier).increment();
        },
      ),
    );
   
  }
}

The FloatingActionButton is set up to call ref.read(counterProvider.notifier).increment(), which increments the count when tapped.

In other words, the expected behavior is:

  1. When the FloatingActionButton is tapped,
  2. counterProvider is incremented,
  3. articlesProvider, which depends on counterProvider, is rebuilt,
  4. Since the number of elements in the List<Article> generated at the end of build() also increases,
  5. The number of rows displayed on the UI eventually increases.

However, in reality, the content on the screen does not change even when the FloatingActionButton is tapped. Why this happens is the main topic of this article.


To state the conclusion first, it is because counterProvider is being disposed of by autoDispose while articlesProvider is awaiting in the middle, but this alone doesn't explain why it behaves that way or how to fix it.

Simply knowing how to avoid this kind of problem isn't very meaningful, so let's take this opportunity to thoroughly investigate the inner workings of Riverpod and use it as a way to deepen our understanding.

Checking Dependencies

In this code, articlesProvider is monitoring counterProvider using ref.watch.

Provider Dependency

I believe your understanding is that autoDispose is, simply put, a mechanism where a provider is automatically disposed of when it is no longer being watched. In other words, it would seem that as long as articlesProvider is alive, counterProvider should also stay alive.

Furthermore, since articlesProvider is being watched by ArticlesPage via ref.watch, as long as this page is displayed, articlesProvider should not be disposed of either.

Widget and Provider Dependency

However, in actual behavior, counterProvider is being disposed of every time the button is tapped. From this, it appears that strictly speaking, counterProvider is disposed of regardless of whether articlesProvider is disposed of. In other words, the explanation that 'it is disposed of when the dependency source is disposed of' is not entirely correct for autoDispose.

Dependencies are reset on every rebuild

Let's follow the internal Riverpod code when a provider is rebuilt. If you actually set a breakpoint and trace back through the StackTrace, you will find the following process in element.dart.[1]

element.dart
void _performBuild() {
  // Save existing dependencies
  _previousDependencies = _dependencies;
  _dependencies = HashMap();

  final previousStateResult = _state;

  // Call build(). Note that it is not awaited.
  buildState();

  if (!identical(_state, previousStateResult)) {
    _notifyListeners(_state!, previousStateResult);
  }

  // Remove the information indicating "I depend on you" from the existing dependency targets
  for (final sub in _previousDependencies!.entries) {
    sub.key
      .._providerDependents.remove(this)
      .._onRemoveListener();
  }
  _previousDependencies = null;
}

What I want to confirm is the part 6 lines from the bottom where, on every provider rebuild, it removes information indicating "I am depending on you" from the dependency target.

To put it another way, even if you ref.watch another provider inside the build() method, the dependency relationship is reset once every time build() is called.

However, normally it behaves as if monitoring continues without us noticing anything. This is because while the old dependencies are reset, ref.watch is executed again within the build() method, and the dependency relationship is reconstructed.

Rebuilds involving asynchronous processing

However, things are a bit different this time.

Let's look back at the build() method of the Articles class.

@riverpod
class Articles extends _$Articles {
  @override
  Future<List<Article>> build() async {
    await Future.delayed(const Duration(milliseconds: 500), () {
      // Simulated data fetching process
    });

    return List.generate(
      ref.watch(counterProvider), 
      (index) => 'article no.$index',
    );
  }
}

As you can see from the code, an asynchronous data fetching process involving await is inserted before the execution of ref.watch.

As you can see from the buildState() call in the code earlier, the provider does not await this build() call itself internally. Therefore, due to the way Flutter works, the code from buildState() onwards is processed with priority before the data fetching process with await.

In other words, the order is such that dependencies are reset as mentioned before, and then, only after all the synchronously processed content beyond that is completed, the build() process of articlesProvider with await is resumed.

The key point here is the part "only after all synchronously processed content is completed".

When rebuilding a Widget, Riverpod finds and disposes of providers that should be discarded by checking if there are any providers that are not being depended on from anywhere, as follows:

element.dart
@override
void mayNeedDispose() {
  final links = _keepAliveLinks;

  if (!maintainState && !hasListeners && (links == null || links.isEmpty)) {
    _container._scheduler.scheduleProviderDispose(this);
  }
}

And since this check is processed synchronously during the rebuild,

  1. The judgment is made before the aforementioned data fetching process with await.
  2. It is determined that there is no provider performing ref.watch (at that point in time).
  3. The state of counterProvider is disposed of.

This is the behavior occurring here.


Solution

Simply put, the cause this time is that processes involving await are deferred, so ref.watch didn't execute in time, leading to the judgment that "counterProvider is no longer depended on by anyone."

In other words, we should move the process involving ref.watch before the await. This is actually the method used to solve the problem in ashdik's project mentioned at the beginning.

@riverpod
class Articles extends _$Articles {
  @override
  Future<List<Article>> build() async {
    // Watch ref.watch first and store the counter value
    final count = ref.watch(counterProvider);

    await Future.delayed(const Duration(milliseconds: 500), () {
      // Simulated data fetching process
    });

    return List.generate(
      count,
      (index) => 'article no.$index',
    );
  }
}

By doing this, ref.watch is executed before the process involving await, allowing articlesProvider to maintain its dependency on counterProvider. As long as a dependent exists, counterProvider will not be automatically disposed of.

Another option is to use @Riverpod(keepAlive: true) to disable autoDispose, but since this significantly changes the lifecycle of counterProvider itself, you should consider whether that is appropriate based on the situation.

ref.watch with Conditional Branches

As explained so far, provider dependencies are reset on every rebuild.

This means you should also be careful when writing code that switches which provider to ref.watch based on conditional branches within the build() method.

// Switch state source based on the value of condition
final count = condition
  ? ref.watch(someCounterProvider)
  : ref.watch(anotherCounterProvider);

In this case, the provider that was not chosen due to the condition will be disposed of at the end of the rebuild.

According to Remi, the policy is that "unlike InheritedWidget, which doesn't stop monitoring once it starts until the observer is removed from the Widget tree, Riverpod determines which states should continue to be monitored on every rebuild and immediately stops unnecessary monitoring."

https://www.youtube.com/watch?v=BJtQ0dfI-RA&t=4320s

If you want to maintain the states of both providers even if condition changes frequently, you need to write the code so that ref.watch is called regardless of the condition:

final someCount = ref.watch(someCounterProvider);
final anotherCount = ref.watch(anotherCounterProvider); 

final count = condition ? someCount : anotherCount;

Summary

In summary, Riverpod's autoDispose is not a mechanism where "it is disposed of when the dependency source is disposed of." More accurately, it is a mechanism where "it is disposed of when the dependency source stops monitoring it." And the judgment that "monitoring has stopped" can occur due to conditional branches or asynchronous processing at times unrelated to the "disposal of the monitoring source."

As Remi mentioned in the Observable<Flutter> video I introduced earlier, Riverpod is not doing anything magical. Obviously, the Riverpod package only performs the processes as implemented in the Dart code.

Just because we app developers write ref.watch in our code doesn't mean it is detected automatically; if for some reason the execution doesn't reach the ref.watch step, Riverpod cannot know that it is "monitoring."

Additionally, to ensure that unnecessary providers are disposed of as early as possible, Riverpod determines whether a provider is needed on every rebuild and disposes of it accordingly.

Summarizing the above, it can be said that accidents where the state is unintentionally disposed of can easily occur if the ref.watch step is not reached due to conditional branches or asynchronous processing.


Riverpod is a package created with a policy that is not bound by the standard behavior or mechanisms of Flutter, for better or worse. Therefore, thinking "this is how it works in standard Flutter" carries the risk of unexpected behavior.

I believe you can incorporate it into your products more safely if you can predict its accurate behavior while reading the official documentation and checking the source code as needed.


脚注
  1. Assertions have been omitted. Comments have also been added. ↩︎

GitHubで編集を提案

Discussion