在flutter中学习bloc时出现错误
错误是
错误:无法在此 Practice4HomePage 小部件上方找到正确的提供程序
发生这种情况是因为您使用了BuildContext
不包括提供者
你的选择。有以下几种常见场景:
-
您在您的目录中添加了一个新的提供商main.dart
并执行热重载。
要修复,请执行热重启。
-
您尝试阅读的提供商处于不同的路线。
提供者是“有范围的”。因此,如果您在路线中插入提供者,那么
其他路由将无法访问该提供商。
-
你用了一个BuildContext
这是您正在尝试阅读的提供者的祖先。
确保 Practice4HomePage 位于您的 MultiProvider/Provider 下。
当您创建提供程序并尝试立即读取它时,通常会发生这种情况。
例如,代替:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// Will throw a ProviderNotFoundError, because `context` is associated
// to the widget that is the parent of `Provider<Example>`
child: Text(context.watch<Example>()),
),
}
考虑使用builder
像这样:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// we use `builder` to obtain a new `BuildContext` that has access to the provider
builder: (context) {
// No longer throws
return Text(context.watch<Example>()),
}
),
}
您必须将该集团提供给您的Practice4HomePage
班级。一种方法是将块提供给整个小部件树,即包装MaterialApp
with BlocProvider
or MultiBlocProvider
。另一种方法是包裹BlocProvider
你正在呼唤的Practice4HomePage
。假设您从 ABC 页面导航到Practice4HomePage
,你可以包裹BlocProvider
在您的导航声明中。
Example:
Navigator.of(context).push(
MaterialPageRoute<HomeForm>(
builder: (context) => BlocProvider<TimerState>(
create: (context) => TimerState(),
child: Practice4HomePage(),
),
),
),
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)