Reputation: 5111
I am using provider package to manage state in Flutter.
This is 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
),
);
}
}
Now, how can I use the application provider in main.dart? I tried doing final app = Provider.of<Application>(context).app;
in build function. However, it throws the following error:
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.
I know that the provider can be accessed by the children but is there any way to access in ancestor/main.dart as well? I need to manage an app wide state.
Upvotes: 2
Views: 2289
Reputation: 276911
That's what Consumer
is here for.
You can use it to do:
Widget build(BuildContext context) {
return Provider<Whatever>(
builder: (_) => Whatever(),
child: Consumer<Whatever>(
builder: (_, whatever, __) {
// todo: use `whatever`
},
),
);
}
Upvotes: 2