final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider<InactivityCubit>(
create: (_) => inject<InactivityCubit>(),
child: MaterialApp.router(
builder: (context, widget) {
return Container(
child: BlocListener<InactivityCubit, InactivityState>(
listener: (context, state) => state.whenOrNull(
showDialog: () {
final currentContext = navigatorKey.currentContext!;
AmazingDialog.show(currentContext!);
return null;
},
),
child: widget,
),
);
},
theme: appTheme,
routerConfig: inject<GoRouter>(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
),
);
}
}
How to open dialog above all screens in flutter, when using go_router? In my code I have an error because navigatorKey.currentContext is null.
2
Answers
Can you try using context of
build
method?Not sure if we can get
context
fromgo_router
.To open a dialog above all screens in Flutter using the provided code snippet, you can use the
showDialog
function along with thenavigatorKey
to ensure the dialog is displayed on top of all screens. :In this code, the
navigatorKey
is set on theMaterialApp.router
widget using thenavigatorKey
property. Then, within theBlocListener
, when theshowDialog
state is triggered,showDialog
is called with thecurrentContext
obtained fromnavigatorKey.currentContext
.With these changes, the dialog will be displayed on top of all screens.