当我们使用访问 Bloc 对象时,如果当前上下文的祖先小部件BlocProvider.of<OrderBloc>(context)不存在,它将返回异常。OrderBloc返回的异常如下:
No ancestor could be found starting from the context that was passed to BlocProvider.of<OrderBloc>().
Run Code Online (Sandbox Code Playgroud)
但当祖先小部件上不存在时,我希望返回null而不是异常。OrderBloc考虑以下场景:
var orderBloc = BlocProvider.of<OrderBloc>(context);
return Container(child: orderBloc == null
? Text('-')
: BlocBuilder<OrderBloc, OrderState>(
bloc: orderBloc,
builder: (context, state) {
// build something if orderBloc exists.
},
),
);
Run Code Online (Sandbox Code Playgroud)