Flutter BLoC 頁面切換問題(記錄)

Randy
3 min readJul 8, 2021

--

開發專案中使用了BLoC進行的狀態更動來更新頁面顯示部分, 類似於如下:

BlocBuilder<BLoC_A, State_A> (
builder: (context, state) {
...
}
)

然而由於BLoC通常會透過BLoC Provider設置並透過Context取用. 在切換頁面時, 會遇到頁面離開過程中跑進了BlocBuilder更新執行, 然而Context卻無法成功拿到對應BLoC而發生如下問題:

Error: Could not find the correct Provider<BLoC_A> above this BlocBuilder<BLoC_A, State_A> WidgetThis happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- You added a new provider in your `main.dart` and performed a hot-reload.
To fix, perform a hot-restart.
- The provider you are trying to read is in a different route.Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.Make sure that BlocBuilder<BLoC_A, State_A> is under your MultiProvider/Provider<BLoC_A>.
This usually happens when you are creating a provider and trying to read it immediately.
...以下略

在使用BlocBuilder未明確指派參數bloc時, 會透過Context往Parent中進行尋找. 因此也可以藉由指派bloc參數去避免掉透過Context尋找而遇到上述的錯誤問題.

Only specify the bloc if you wish to provide a bloc that will be scoped to a single widget and isn’t accessible via a parent BlocProvider and the current BuildContext.[1.]

Reference
[1.] https://github.com/felangel/bloc/tree/master/packages/flutter_bloc

--

--