Flutter Provider 解释:发生异常。提供者未发现异常
我是新来的扑腾。我有下面的代码,但它没有运行。我知道如何修复错误(一种解决方案)。但我想理解这里为什么它没有运行的概念。此外,还有所有其他不同的解决方案来解决此问题。
我想知道有关以下代码的更详细解释为什么会发生错误?
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Provider<String>(
create: (context) => "Passing Data",
child: MaterialApp(
title: Provider.of<String>(context),
home: HomePage(),
),
);
}
}
I'm new to flutter. I've got the below code and it's not running. I know how to fix the error (one solution). But I wanted to understand the concept here of why it's not running. Also, all the other different solutions to fix this issue.
I would like to know much detailed explanation about the below code why the error occurred?
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Provider<String>(
create: (context) => "Passing Data",
child: MaterialApp(
title: Provider.of<String>(context),
home: HomePage(),
),
);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以阅读 BuildContext、Provider 和 InheritedWidget,但我也可以提供一个简洁的解释:
您不能在返回它的同一个小部件中使用Provider。它必须是继承的(即提供者必须来自父级或祖先小部件)或具有单独的上下文。您必须在上面创建一个单独的小部件(即父小部件),然后包含 MaterialApp(如果您仍想在那里使用它)。这主要是因为上下文引用。上下文用于从小部件的祖先中提取数据(在本例中,是上面提供的值),而 Provider 无非是 InheritedWidget 的包装器,因此为了获取提供的值,上下文必须是继承的或者是它自己的上下文。
在您的情况下,提供程序必须位于父小部件上,以便您可以继承传递给您的值,或者您必须使用诸如 Consumer 小部件或 Builder 之类的东西提供自己的上下文的小部件,但从不使用相同的上下文来注入和获取提供者。
您可以这样做,其中Builder小部件提供自己的上下文:
或者像这样,您在runApp中看到我们如何将 Provider 包裹在 MyApp 周围,创建一个层次结构,允许 MyApp 小部件继承上下文,您可以从中安全地获取提供的值。
You can read up on BuildContext, Provider and InheritedWidget, but I also can offer a condensed explanation:
You cannot use the Provider within the same widget in which you're returning it. It must be inherited (i.e. the Provider must come down from a parent or ancestor widget) or have a separate context. You must either create a separate widget above (i.e. a parent widget) that then includes the MaterialApp if you still want to use it there. This is mostly because of the Context reference. The context is used to pull data from the widget's ancestors (in this case, a provided value from above), and Provider is nothing more than a wrapper around InheritedWidget, therefore in order to fetch the provided value, the context must be inherited or be its own context.
In your case, the Provider must be either located on a parent widget so you can inherit the value being handed down to you, or you must use something like a Consumer widget or a Builder widget which supply their own context, but never use the same context both for injecting and fetching the provider.
You either can do it like this, where the Builder widget supplies its own context:
or like this, where you see in the runApp how we wrap the Provider around the MyApp, creating a hierarchy, allowing for the context to be inherited by the MyApp widget, from which you can safely fetch the provided value.