繁体   English   中英

在 flutter 的同一小部件中使用 Provider

[英]Using Provider in the same widget in flutter

我已经在我的小部件中声明了 MultipleProviders,我想通过将变量添加到 ThemeData Primary 样本来使用它来更改应用程序的颜色,但它给了我这个与提供程序相关的错误。 我已经在其他小部件中使用它并且它正在工作。我认为我收到了这个错误,因为我在同一个小部件中使用它我该如何解决它?

void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var u = Provider.of<prov>(context);
    return MultiProvider(
      providers: [ChangeNotifierProvider(create: (_)=>prov())],
      child: GetMaterialApp(
        theme: ThemeData(primarySwatch: u.col),
        title: 'Material App',
        home: f(),
      ),
    );

  }
} 

这是错误

错误:在此 MyApp 小部件上方找不到正确的提供程序

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

  • 您在main.dart中添加了一个新提供程序并执行了热重载。 要修复,请执行热重启。

  • 您尝试读取的提供程序位于不同的路径中。

    提供者是“范围的”。 因此,如果您在路由中插入提供程序,那么其他路由将无法访问该提供程序。

  • 您使用的BuildContext是您尝试读取的提供程序的祖先。

    确保 MyApp 在您的 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>()), } ), }

您收到错误是因为您使用的context无权访问provider

解决方案就像它在错误消息中所说的那样:您可以为您的provider使用builder而不是child属性。 这会创建一个读取创建的provider的新context

您应该将build方法更改为此。

  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [ChangeNotifierProvider(create: (_)=>prove())],
    
      //From here is where you make the change
    
      builder: (context, child) {
      var u = Provider.of<prov>(context);
    
      return GetMaterialApp(
        theme: ThemeData(primarySwatch: u.col),
        title: 'Material App',
        home: f(),
      ),
    );
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM