Home > Software design >  getting error in navigation btw screens in flutter
getting error in navigation btw screens in flutter

Time:10-08

I am trying to navigate btw screens using gesture detector but getting an error message how do i fix this?

Error

======== Exception caught by gesture =============================================================== The following assertion was thrown while handling a gesture: Navigator operation requested with a context that does not include a Navigator.

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. When the exception was thrown, this was the stack: C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/internal/js_dev_runtime/private/ddc_runtime/errors.dart 236:49 throw packages/flutter/src/widgets/navigator.dart 2732:9 packages/flutter/src/widgets/navigator.dart 2738:14 of packages/task1/main.dart 78:10 [_navigateToNextScreen] packages/task1/main.dart 60:21 ... Handler: "onTap" Recognizer: TapGestureRecognizer#ae0a6 debugOwner: GestureDetector state: possible won arena finalPosition: Offset(857.6, 553.0) finalLocalPosition: Offset(264.6, 206.2) button: 1 sent tap down

My code:

   import 'package:flutter/material.dart';
   
   import 'package:url_launcher/url_launcher.dart';
   
   
   void main() {
     runApp(MyApp());
   }
   
   class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
     @override
     Widget build(BuildContext context) {
       return MaterialApp(
         home: Scaffold(
           body: Column(
   
   
             children:  <Widget>[
               Padding(
                 padding: const EdgeInsets.all(18.0),
                 child: Text(
                   'choose an option',
                   style: TextStyle(
                     fontSize: 32,
                     color: Colors.black87,
                   ),
                 ),
               ),
               Center(
                 child: ClipRRect(
                   borderRadius: BorderRadius.all(Radius.circular(45.0)),
                   child: Image(
                     width: 350,
                     image: NetworkImage(
                         'https://images.unsplash.com/photo-1451187580459-43490279c0fa?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=872&q=80'),
                   ),
                 ),
               ),
   
               SizedBox(
                 height: 40.0,
               ),
               Center(
                 child: ClipRRect(
                   borderRadius: BorderRadius.all(Radius.circular(45.0)),
                   child: GestureDetector(
                     onTap: () {
                       _navigateToNextScreen(context);
                     },
                     child: Image(
                       width: 350,
                       image: NetworkImage(
                           "https://images.unsplash.com/photo-1555967522-37949fc21dcb?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8c2Nob2xhcnxlbnwwfHwwfHw=&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"),
                     ),
                   ),
                 ),
               ),
             ],
           ),
         ),
       );
     }
   
     void _navigateToNextScreen(BuildContext context) {
       Navigator.of(context)
           .push(MaterialPageRoute(builder: (context) => HomePage()));
     }
   }
   
   
   class HomePage extends StatelessWidget {
     void _launchUrl(String _url) async => await launch(_url);
   
     @override
     Widget build(BuildContext context) {
       return Scaffold(
         appBar: AppBar(
           title: Text('Tech News'),
         ),
         body: SingleChildScrollView(
           child: Center(
             child: Column(
               children: <Widget>[
                 SizedBox(
                   height: 40.0,
                 ),
                 ElevatedButton(
                   child: Text('article1'),
                   onPressed: () {
                     _launchUrl(
                         "https://theprint.in/opinion/mark-zuckerberg-and-elon-musks-ai-gamble-shows-why-the-tech-is-not-ready-for-prime-time/744962/");
                   },
                 ),
                 SizedBox(
                   height: 40.0,
                 ),
                 ElevatedButton(
                   child: Text('article2'),
                   onPressed: () {
                     _launchUrl(
                         "https://www.livemint.com/market/stock-market-news/wall-street-slammed-by-rotation-out-of-big-tech-nasdaq-falls-over-2-11633360763474.html");
                   },
                 ),
                 SizedBox(
                   height: 40.0,
                 ),
                 ElevatedButton(
                   child: Text('article3'),
                   onPressed: () {
                     _launchUrl(
                         "https://www.business-standard.com/article/companies/bengaluru-startup-offers-three-day-work-week-to-attract-tech-talent-121100400945_1.html");
                   },
                 ),
                 SizedBox(
                   height: 40.0,
                 ),
                 new InkWell(
                     child: new Text('Open Browser'),
                     onTap: () => launch(
                         'https://docs.flutter.io/flutter/services/UrlLauncher-class.html')),
               ],
             ),
           ),
         ),
       );
     }
   }
   ```

CodePudding user response:

What is Navigator.of(context)?

When you call Navigator.of(context) flutter tries to get the Navigator of the given context.

Why do you get the error?

Navigator is put in the widget tree be MaterialApp, therefore, any context bellow MaterialApp should be able to call Navigator.of(context).

You are using the context of MyApp which is above MaterialApp, hence the error.

Solution

You need to get a context which is bellow MaterialApp. An easy way to achieve this is to use the Builder widget.

Here is your code with the use of Builder to get the right context:

MaterialApp(
  home: Builder(
    builder: (context) {
      return Scaffold(
        body: Column(
          children:  <Widget>[
            Padding(
              padding: const EdgeInsets.all(18.0),
              child: Text(
                'choose an option',
                style: TextStyle(
                  fontSize: 32,
                  color: Colors.black87,
                ),
              ),
            ),
            Center(
              child: ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(45.0)),
                child: Image(
                  width: 350,
                  image: NetworkImage(
                      'https://images.unsplash.com/photo-1451187580459-43490279c0fa?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=872&q=80'),
                ),
              ),
            ),

            SizedBox(
              height: 40.0,
            ),
            Center(
              child: ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(45.0)),
                child: GestureDetector(
                  onTap: () {
                    _navigateToNextScreen(context);
                  },
                  child: Image(
                    width: 350,
                    image: NetworkImage(
                        "https://images.unsplash.com/photo-1555967522-37949fc21dcb?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8c2Nob2xhcnxlbnwwfHwwfHw=&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }
  ),
);
  • Related