简体   繁体   中英

Showing Dialog with Auto_Route and BlocListener

I'm developing an app that diplays an alert every time the user turns off the device's Wifi and Mobile Data. I'm also using Auto_Route for navigation.

Here's the code so far:

class AppWidget extends StatelessWidget {
  AppWidget({super.key});
  final GlobalKey<ScaffoldMessengerState> messengerKey = GlobalKey<ScaffoldMessengerState>();
  @override
  Widget build(BuildContext context) {
    return RepositoryProvider(
      create: (_) => getIt<CPlusNetworkRepository>(),
      child: BlocProvider(
          create: (_) => getIt<ConnectionStatusBloc>()
          ..add(const StreamSubsricptionRequested()),
          child: BlocListener<ConnectionStatusBloc, ConnectionStatusState>(
             listener: (context, state) {
                state.map(
                  connected: (_) {},
                  disconnected: (_) async {
                    WidgetsBinding.instance.addPostFrameCallback((_) async{
                       await showCupertinoDialog(
                         context: context,
                         builder: (context) => const CupertinoAlertDialog(
                           title: Text('Alert'),
                           content: Text('Please switch on Wifi/Mobile Data'),
                         ),
                       );
                    });
                  },
                  unknown: (_) {},
                );
             },
          child: MaterialApp.router(  
             scaffoldMessengerKey: messengerKey,
             routeInformationParser: appRouter.defaultRouteParser(),
             routerDelegate: appRouter.delegate(),
          ),
        ),
      ),
    );
  }
}

I'm getting this error:

E/flutter ( 9910): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.

E/flutter ( 9910): The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.

I know there's somethig inherently wrong with what I'm trying to do but I can't seem to find the correct way to approach this.

Any suggestions?

Thanks in advance.

You're trying to show a Dialog, which requires a Navigator to be placed anywhere before it in the widget tree. A solution would be to place the listener below your Material , so it has Navigator to find up in his BuildContext

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM