我正在使用提供程序包来管理 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中访问?我需要管理应用范围的状态。
这就是Consumer
的目的。
您可以使用它来执行:
Widget build(BuildContext context) {
return Provider<Whatever>(
builder: (_) => Whatever(),
child: Consumer<Whatever>(
builder: (_, whatever, __) {
// todo: use `whatever`
},
),
);
}