0

I used a Future in the StatefulWidget, and the Future can still run then after the StatefulWidget dispose. When I need to change the StatefulWidget in then, it is not safe.

My ideal situation should be that the StatefulWidget where the Future is located is cancelled after dispose. But I found that there is no way to cancel the Future. It has only three states: not completed, completed with value, and completed with error.

Then I found a way to cancel the Future, but it is still not perfect, I have to use Stream or CancelableOperation.

Is there a better way to handle the life cycle of StatefulWidget and Future?

Nullable
  • 761
  • 5
  • 17
  • 1
    see how `FutureBuilder` checks if the `Future` can be used: https://github.com/flutter/flutter/blob/c19845a8c3/packages/flutter/lib/src/widgets/async.dart#L628 – pskink Nov 10 '21 at 09:09
  • @pskink Thanks, although I did not use FutureBuilder, I still need to learn – Nullable Nov 11 '21 at 02:30
  • so do the same thing in your code, where you are calling `Future.then` method – pskink Nov 11 '21 at 06:15
  • @pskink I finally understood that `FutureBuilder` uses `_activeCallbackIdentity `to control whether the then needs to be executed, usually there is no problem. But I often use `await`, if I use it like this, I lose `await`, and I always have to couple the `Future` and `the widget`. I read the cancel program of [dio](https://github.com/flutterchina/dio) and it solved my problem. I only need to pass in a `CancelToken` for each `Future` method that needs to be cancelled, which can solve the cancellation and continue to use `await`. – Nullable Nov 11 '21 at 07:53

0 Answers0