i'm trying to create a multiprovider in a class. but it doesn't work same as declaring multiproviders in main.dart above material app.
class Chat extends StatelessWidget {
const Chat({ Key? key }) : super(key: key);
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<ChatProvider>( create: (context) => ChatProvider()),
ChangeNotifierProvider<MessageProvider>( create: (context) => MessageProvider()),
],
child: ChatMainScreen(),
// MaterialApp(
// debugShowCheckedModeBanner: false,
// home: ChatMainScreen(),
// )
);
}
}
I'm navigating to another screen from ChatMainScreen to a new screen(ChatRoom) where this issue arises.(ChatMainScreen => ChatRoom)
if i wrap my ChatMainScreen with another material app than it seems to work. but is it ok to have another material app inside a material app?.
Also with material app parent to ChatMainScreen routing back is not working correctly. if i press back button from ChatRoom screen, instead of getting popped back to chatMainScreen, it is popped out to the screen from where i pushed to ChatMainScreen
When using Provider understanding the context is important. To have access to a Provider everywhere you can put it above the MaterialApp and it works fine. Now MaterialApp from flutter is most certainly creating a Navigator object internally so that it can maintain a stack of the child routes and having the MultiProvider above this object allows you to have access to these Providers.
In your case it seems you don't want to have the Providers above the MaterialApp, so I can think of two solutions:
Chat widget you have created the MultiProvider and used ChatMainScreen widget as the child so this is good because in your ChatMainScreen widget's context is below the MultiProvider so you have access to it. Somewhere in your ChatMainScreen you push another route which opens ChatRoom widget. If you want access to the Providers mentioned in MultiProvider you need to push a MultiProvider like:Navigator.push(
context,
MaterialPageRoute(
builder: (_) => MultiProvider(
providers: [
ChangeNotifierProvider.value(value: Provider.of<ChatProvider>(context,
listen: false),
...
],
child: ChatRoom()
Using ChangeNotifierProvider.value will give you access to the same Provider in the new route.
Chat widget.
return MultiProvider(
providers: [
ChangeNotifierProvider<ChatProvider>( create: (context) => ChatProvider()),
ChangeNotifierProvider<MessageProvider>( create: (context) => MessageProvider()),
],
child: Navigator(
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute(
builder: (context) {
return ChatMainScreen();
);
I think the 1st solution might be better for you and you should not have more than 1 MaterialApp widget in your app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With