【问题标题】:Using provider in ancestor在祖先中使用提供者
【发布时间】:2019-09-29 16:19:56
【问题描述】:

我正在使用提供程序包来管理 Flutter 中的状态。

这是 main.dart:

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Application>(
      builder: (_) => Application(),
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: HomeScreen(),
        initialRoute: AppRoutes.home
      ),
    );
  }
}

现在,我如何在 main.dart 中使用应用程序提供程序?我尝试在构建函数中执行final app = Provider.of&lt;Application&gt;(context).app;。但是,它会引发以下错误:

Error: Could not find the correct Provider<Application> above this MyApp Widget

To fix, please:

  * Ensure the Provider<Application> is an ancestor to this MyApp Widget
  * Provide types to Provider<Application>
  * Provide types to Consumer<Application>
  * Provide types to Provider.of<Application>()
  * Always use package imports. Ex: `import 'package:my_app/my_code.dart';
  * Ensure the correct `context` is being used.

我知道孩子可以访问提供者,但是有什么方法可以在祖先/main.dart 中访问吗?我需要管理应用范围的状态。

【问题讨论】:

    标签: flutter dart provider


    【解决方案1】:

    这就是Consumer 的用途。

    你可以用它来做:

    Widget build(BuildContext context) {
      return Provider<Whatever>(
        builder: (_) => Whatever(),
        child: Consumer<Whatever>(
          builder: (_, whatever, __) {
            // todo: use `whatever`
          },
        ),
      );
    }
    

    【讨论】:

    • 如何调用提供者方法?例如,通常我会 -> Provider.of&lt;Application&gt;(context).getApp();。现在在这种情况下我该怎么办?
    猜你喜欢
    • 2020-11-28
    • 2012-06-21
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2019-06-26
    • 1970-01-01
    • 2021-07-30
    相关资源
    最近更新 更多