拦截返回键时无法获取WatchSkSelectClubBloc问题求助
问题排查:拦截返回键时无法获取Bloc实例并重置状态
问题描述
拦截返回键时希望将主Bloc的状态重置为初始状态,因此在按下返回键时添加重置事件,但操作无法正常执行。报错提示BlocProvider.of()调用的context中不存在WatchSkSelectClubBloc,尽管Widget Tree显示该Bloc已被提供,且该模块断点无效。
报错堆栈
_onBackPressed Builder Builder(dependencies: [ScrollConfiguration, _LocalizationsScope-[GlobalKey#488f2]]) ======== Exception caught by gesture =============================================================== The following assertion was thrown while handling a gesture: BlocProvider.of() called with a context that does not contain a WatchSkSelectClubBloc. No ancestor could be found starting from the context that was passed to BlocProvider.of(). This can happen if the context you used comes from a widget above the BlocProvider. The context used was: Builder(dependencies: [ScrollConfiguration, _LocalizationsScope-[GlobalKey#488f2]]) ...
调用Widget代码
Navigator.of(context).push( MaterialPageRoute( builder: (context) => WatchSkSelectTornooiPage( parentContext: context, clubname: state.clickedOnClubnameFromDbForWedstrijdtafel, anonymousAllowed: true, activeWts: state.activeWts, tournamentId: state.clickedOnTournamentIdFromDbForWedstrijdtafel, )), );
抛出异常的代码
class WatchSkSelectTornooiPage extends StatefulWidget { final BuildContext parentContext; ... void _onBackPressed(context) { // Set state back to init to refresh clublist if (kDebugMode) { print("_onBackPressed ${widget.parentContext} ${context}"); } BlocProvider.of<WatchSkSelectClubBloc>(context) .add(WatchSkRefreshSelectClubEvent()); Navigator.of(context).pop(); } ... }
问题原因与解决方案
原因
_onBackPressed方法中使用的context是当前WatchSkSelectTornooiPage页面的上下文,而WatchSkSelectClubBloc是在父页面的Widget树中提供的,当前页面的上下文无法向上查找到该Bloc实例。虽然你已经将父页面的parentContext传入当前页面,但代码中并未使用它来获取Bloc。
解决方案
直接使用传入的parentContext来获取Bloc实例,修改_onBackPressed方法:
void _onBackPressed(context) { // Set state back to init to refresh clublist if (kDebugMode) { print("_onBackPressed ${widget.parentContext} ${context}"); } // 使用父页面的context获取Bloc BlocProvider.of<WatchSkSelectClubBloc>(widget.parentContext) .add(WatchSkRefreshSelectClubEvent()); Navigator.of(context).pop(); }
额外验证:确保传入的parentContext确实处于BlocProvider<WatchSkSelectClubBloc>的子树中,也就是父页面的context是在BlocProvider创建之后的上下文,这样才能正确找到Bloc实例。
内容的提问来源于stack exchange,提问作者Hoegje
相关产品推荐
相关产品推荐

