When we use BlocProvider.of<OrderBloc>(context)
to access Bloc object, it returns an exception if no OrderBloc
exists on ancestor widgets of current context. Returned exceptions as follows:
No ancestor could be found starting from the context that was passed to BlocProvider.of<OrderBloc>().
But I want return null
instead of exceptions when no OrderBloc
exists on ancestor widgets. Consider following scenario:
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.
},
),
);