Dart Provider:在直子上不可用 [英] Dart Provider: not available at the immediate child

查看:80
本文介绍了Dart Provider:在直子上不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  @override
  Widget build(BuildContext context) {
    return BlocProvider<HomeBloc>(
        create: (context) {
          return HomeBloc(homeRepo: HomeRepository());
        },
        child: BlocProvider.of<HomeBloc>(context).state is HomeStateLoading
            ? CircularProgressIndicator()
            : Container());
  }

我对错误感到困惑:

BlocProvider.of() called with a context that does not contain a Bloc of type HomeBloc.
No ancestor could be found starting from the context that was passed to
BlocProvider.of<HomeBloc>().

我不是直接在其直接父级中创建HomeBloc吗?要什么

Didn't I just create the HomeBloc at its immediate parent? What does it want?

推荐答案

您正在使用传递到窗口小部件类的build方法中的context查找父级BlocProvider.但是,就您的窗口小部件类而言,上下文是窗口小部件树.因此,您的BlocProvider.of正在寻找作为 widget类的父级的BlocProvider.如果要获取作为直接父级的提供者,则需要一个新的context对象,其中BlocProvider是小部件树中的祖先.最简单的方法是使用Builder小部件:

You are using the context passed into the build method of your widget class to look for a parent BlocProvider. However, that context is the widget tree as far as your widget class sees it. Because of this, your BlocProvider.of is looking for a BlocProvider that is a parent of your widget class. If you want to get the provider that is the immediate parent, you need a new context object in which the BlocProvider is an ancestor in the widget tree. The easiest way to do this is with a Builder widget:

@override
Widget build(BuildContext context) {
  return BlocProvider<HomeBloc>(
    create: (context) {
      return HomeBloc(homeRepo: HomeRepository());
    },
    child: Builder(
      builder: (newContext) => BlocProvider.of<HomeBloc>(newContext).state is HomeStateLoading
          ? CircularProgressIndicator()
          : Container(),
    ),
  );
}

话虽如此,创建一个提供程序然后立即尊敬该提供程序是非常多余的.提供程序用于在窗口小部件树的下方检索内容,通常不用于直接后代.在这种情况下,使用提供程序是过大的,实际上没有任何理由不只是让bloc成为您的类的一个字段并直接引用它.

That being said, it's pretty redundant to create a provider and then immediately reverence the provider. Providers are for retrieving stuff further down the widget tree, not typically for immediate descendants. In this case, using a provider is overkill and there isn't really any reason to not just have the bloc be a field of your class and reference it directly.

这篇关于Dart Provider:在直子上不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆