Flutter Hero widget and Bloc error

Quan Ngo
1 min readApr 15, 2022

When you using Hero widget like this

Hero(
tag: "test_hero",
child: BlocBuilder<TestBloc, TestBlocState>(
builder: (context, state) {
return InkWell(
onTap: () {
Navigator.of(context).pop();
},
);
},
),
)

Flutter will throw the error when you navigate to the screen

Error: Could not find the correct Provider<TestBloc> above this BlocBuilder<TestBloc, TestBlocState> Widget

The reason explained below:

When we push from screen A to screen B, both screen has a Hero widget with the same tag, Flutter will get the Hero widget in the screen B then insert it into a Overlay, then animate its position from the position of Hero widget in screen A to the position of Hero widget in screen B.

So when we use the BlocBuilder inside the Hero widget, when the hero is flying, the BlocBuilder will use the context of the Overlay, so it cannot find the Bloc (because the Bloc is in the context of screen B, not the Overlay context).

So, below code will fix the problem, we will get the bloc from screen B context, then provide it inside the Hero widget

Builder(
builder: (context) {
final testBlocInstance = context.read<TestBloc>();
return Hero(
tag: "test_hero",
child: BlocProvider.value(
value: testBlocInstance,
child: BlocBuilder<TestBloc, TestBlocState>(
builder: (context, state) {
return InkWell(
onTap: () {
Navigator.of(context).pop();
},
);
},
),
),
);
}
)

--

--