【发布时间】: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<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 中访问吗?我需要管理应用范围的状态。
【问题讨论】: