在祖先中使用提供者

时间:2019-09-29 16:19:56

标签: flutter dart provider

我正在使用提供程序包来管理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<Application>(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中也可以访问吗?我需要管理应用范围内的状态。

1 个答案:

答案 0 :(得分:1)

这就是Consumer的用途。

您可以使用它来执行以下操作:

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