I am working on the iPad and I have set up the screen to be SplitScreens
. Thus I have two Navigators
side by side. However, when I call to show a Snackbar
in one navigator with it's specific context, the Snackbar
is still showing on both navigators.
GlobalKey<NavigatorState> secondSplitNavigatorKey = GlobalKey<NavigatorState>();
GlobalKey<NavigatorState> firstSplitNavigatorKey = GlobalKey<NavigatorState>();
SplitView(
menu: Navigator(
key: firstSplitNavigatorKey,
onGenerateRoute: (routeSettings) {
return MaterialPageRoute(
builder: (context) =>
const KursplanungScreen(title: 'Demo App'),
);
},
),
content: Navigator(
key: secondSplitNavigatorKey,
onGenerateRoute: (routeSettings) {
return MaterialPageRoute(
builder: (context) => const Scaffold(
body: Center(
child: Text(
"Herzlich Willkommen!"))),
);
},
),
menuWidth: 300,
),
Later I call this in the second navigator:
ElevatedButton(
onPressed: () {
showSnackbar(
secondSplitNavigatorKey.currentState!.context,
"Bitte tragen Sie einen Fachnamen ein!");
},
child: const Icon(
Icons.add,
),
),
I only want the Snackbar to be showing in the second Navigator/Screen only!
CodePudding user response:
If you want to show snack bar in one screen(I assume in KursplanungScreen
), You can wrap your KursplanungScreen's Scaffold whit ScaffoldMessenger
and pass it global key and use that to show snack bar like this:
class KursplanungScreen extends StatelessWidget {
KursplanungScreen({Key? key, required this.title}) : super(key: key);
final String title;
final GlobalKey<ScaffoldMessengerState> _scaffoldKey =
new GlobalKey<ScaffoldMessengerState>();
@override
Widget build(BuildContext context) {
return ScaffoldMessenger(
key: _scaffoldKey,
child: Scaffold(
body: Container(
child: Center(
child: ElevatedButton(
onPressed: () {
var snackBar = SnackBar(content: Text('Hello World'));
_scaffoldKey.currentState?.showSnackBar(snackBar);
},
child: const Icon(
Icons.add,
),
),
),
),
),
);
}
}
SplitView class:
class SplitView extends StatelessWidget {
const SplitView(
{Key? key,
required this.menu,
required this.content,
required this.menuWidth})
: super(key: key);
final Navigator menu;
final Navigator content;
final double menuWidth;
@override
Widget build(BuildContext context) {
return Row(
children: [
SizedBox(width: menuWidth, child: menu),
Expanded(child: content)
],
);
}
}
and use it like this:
SplitView(
menu: Navigator(
key: firstSplitNavigatorKey,
onGenerateRoute: (routeSettings) {
return MaterialPageRoute(
builder: (context) => KursplanungScreen(title: 'Demo App'),
);
},
),
content: Navigator(
key: secondSplitNavigatorKey,
onGenerateRoute: (routeSettings) {
return MaterialPageRoute(
builder: (context) => const Scaffold(
body: Center(child: Text("Herzlich Willkommen!"))),
);
},
),
menuWidth: 300,
)