Error: Could not find the correct Provider<TimerState> above this Practice4HomePage Widget Flutter(BLoc)

Error: Could not find the correct Provider<TimerState> above this Practice4HomePage Widget Flutter(BLoc)

我在flutter中学习bloc时出错

错误是 错误:在此 Practice4HomePage 小部件上方找不到正确的提供者

发生这种情况是因为您使用的 BuildContext 不包括提供商 你的选择。有几个常见的场景:

首先,您需要使用 BlocProvider 而不是 Provider,其次,使用 Builder 包装您的子窗口小部件,因为 BlocProvider.of(context)(或在本例中为 context.watch())从当前在树上查找您的 BlocProvider,并且您使用与您提供的 Bloc 相同的上下文,因此它无法在树上找到它,因为它处于同一级别(相同的上下文),因此只需使用由提供的建议你的错误,或者像这样:

Widget build(BuildContext context) {
  return BlocProvider<Example>(
    create: (_) => Example(),
    child: Builder(builder: (context) => Text(context.watch<Example>())),
  ),
}

或者您可以将 Text 小部件提取到新的 StatelessWidget 中,这也可以工作,因为它将拥有自己的(新的)BuildContext,如下所示:

class ParentWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<Example>(
      create: (_) => Example(),
      child: ChildWidget(),
    ),
  }
}

class ChildWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text(context.watch<Example>());
  }
}

您必须向您的 Practice4HomePage class 提供集团。一种方法是将 bloc 提供给整个小部件树,即用 BlocProviderMultiBlocProvider 包装 MaterialApp。另一种方法是将您调用的 BlocProvider 换行 Practice4HomePage。因此,假设您要从 ABC 页面导航到 Practice4HomePage,您可以将 BlocProvider 包装在导航语句中。

示例:

Navigator.of(context).push(
  MaterialPageRoute<HomeForm>(
    builder: (context) => BlocProvider<TimerState>(
      create: (context) => TimerState(),
      child: Practice4HomePage(),
    ),
  ),
),