Flutter:如果存在则获取提供者,否则返回 null 而不是异常

时间:2021-04-30 11:02:41

标签: flutter bloc flutter-provider flutter-bloc

当我们使用 BlocProvider.of<OrderBloc>(context) 访问 Bloc 对象时,如果当前上下文的祖先小部件上不存在 OrderBloc,它将返回异常。返回的异常如下:

No ancestor could be found starting from the context that was passed to BlocProvider.of<OrderBloc>().

但是当祖先小部件上不存在 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.
          },

        ),          
);

1 个答案:

答案 0 :(得分:1)

你可以像这样用 try/catch 包裹那一行:

var orderBloc;
try {
  orderBloc = BlocProvider.of<OrderBloc>(context);
} catch (e) {}

return Container(child: orderBloc == null
  ? Text('-')
  : BlocBuilder<OrderBloc, OrderState>(
      bloc: orderBloc,
      builder: (context, state) {
        // build something if orderBloc exists.
      },
    ),          
);

编辑:

如果你想减少样板:

extension ReadOrNull on BuildContext {
  T? readOrNull<T>() {
    try {
      return read<T>();
    } on ProviderNotFoundException catch (_) {
      return null;
    }
  }
}

那么您的代码将是:

var orderBloc = context.readOrNull<OrderBloc>();

return Container(child: orderBloc == null
  ? Text('-')
  : BlocBuilder<OrderBloc, OrderState>(
      bloc: orderBloc,
      builder: (context, state) {
        // build something if orderBloc exists.
      },
    ),          
);