从Consumer Flutter正确访问ChangeNotificationProvider



我无法从Consumer<QuestionProvider>访问我的ChangeNotifierProvider<QuestionProvider>,但我不明白为什么,与它的提供者相比,它在小部件树中定义得更深。

我在这里定义了我的提供商:

body: GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: ChangeNotifierProvider<QuestionProvider>(
//TODO : question provider arguments should come from internet
create: (newContext) => QuestionProvider([], pageController),
child: Column(
children: [
TypeAndSettingsRow(),

消费者在TypeAndSettingsRow:中定义的下一个小部件中定义

class TypeAndSettingsRow extends StatefulWidget {
@override
State<TypeAndSettingsRow> createState() => _TypeAndSettingsRowState();
}
class _TypeAndSettingsRowState extends State<TypeAndSettingsRow> {
@override
Widget build(BuildContext context) {
void showPopoverType() {
int thisIsTrue = 0;
double size = MediaQuery.of(context).size.width * 0.9;
showPopover(
context: context,
tion(milliseconds: 150),
bodyBuilder: (context) => CheckboxListTileRow(),

最后是CheckboxListTileRow:

class _CheckboxListTileRowState extends State<CheckboxListTileRow> {
@override
Widget build(BuildContext context) {
return Consumer<QuestionProvider>(builder: ((context, value, child) {

QuestionProvider:

class QuestionProvider extends ChangeNotifier {

当我打开CheckboxListTileRow时,这是错误:

Error: Could not find the correct Provider<QuestionProvider> above this Consumer<QuestionProvider> Widget
This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
You added a new provider in your `main.dart` and performed a hot-reload.
To fix, perform a hot-restart.
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that Consumer<QuestionProvider> is under your MultiProvider/Provider<QuestionProvider>.

我不明白哪个是问题所在,因为我的提供者是在上面的小部件树中定义的,所以它应该是可访问的。

也许contexts有一些错误?

编辑

发现问题是showPopover形式的popover包,当我尝试用showPopover内的Consumer访问ChangeNotifierProvider时,会抛出此错误,但如果我在外部执行,则它可以工作。可能它创建了一个新的路由,我再也无法访问我的提供商了。希望这个新提示能帮助解决问题,因为这个问题仍然悬而未决。

Make sure that Consumer<QuestionProvider> is under your MultiProvider/Provider<QuestionProvider>. 

这意味着您在main.dart文件中没有提到提供者类。为此,您必须使用以下代码。

Provider(
create: (_) => QuestionProvider(),
child: MyApp(),
),

如果您有多个提供程序,则可以使用以下代码。

MultiProvider(
providers: [
QuestionProvider(),
.....
]
)

为什么使用changeNotificationProvider在小部件树的根上?如果你不需要喜欢它,你可以在你的小部件树中的任何地方使用它,并使用消费者,因为它在孩子身上而不是另一个小部件

相关内容

  • 没有找到相关文章

最新更新