skip to Main Content

im new in flutter and i have this button error that wont navigate to different pages.

so i have a "HomePage" that have a button to navigate to "ReminderHomePage". but when i try to press it it show 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 266:49      throw_packages/flutter/src/widgets/navigator.dart 2554:9                                                                             <fn>
packages/flutter/src/widgets/navigator.dart 2560:14                                                                            of    
packages/flutter/src/widgets/navigator.dart 2019:34                                                                            push  
packages/medreminder/home_page.dart 42:32                                                                                      <fn>  
packages/flutter/src/material/ink_well.dart 1072:21
handleTap
packages/flutter/src/gestures/recognizer.dart 253:24
invokeCallback
packages/flutter/src/gestures/tap.dart 627:11
handleTapUp
packages/flutter/src/gestures/tap.dart 306:5
[_checkUp]
packages/flutter/src/gestures/tap.dart 239:7
handlePrimaryPointer
packages/flutter/src/gestures/recognizer.dart 615:9
handleEvent
packages/flutter/src/gestures/pointer_router.dart 98:12
[_dispatch]
packages/flutter/src/gestures/pointer_router.dart 143:9                                                                        <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/linked_hash_map.dart 21:13
forEach
packages/flutter/src/gestures/pointer_router.dart 141:17
[_dispatchEventToRoutes]
packages/flutter/src/gestures/pointer_router.dart 127:7                                                                        route 
packages/flutter/src/gestures/binding.dart 460:19
handleEvent
packages/flutter/src/gestures/binding.dart 440:14
dispatchEvent
packages/flutter/src/rendering/binding.dart 337:11
dispatchEvent
packages/flutter/src/gestures/binding.dart 395:7
[_handlePointerEventImmediately]
packages/flutter/src/gestures/binding.dart 357:5
handlePointerEvent
packages/flutter/src/gestures/binding.dart 314:7
[_flushPointerEventQueue]
packages/flutter/src/gestures/binding.dart 295:7
[_handlePointerDataPacket]
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/platform_dispatcher.dart 1183:13
invoke1
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/platform_dispatcher.dart 244:5
invokeOnPointerDataPacket
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 147:39
[_onPointerData]
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 653:20                    <fn>  
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 594:14                    <fn>  
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 288:16
loggedHandler
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 179:80                    <fn>  
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14
_checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39  dcall 

Handler: "onTap"
Recognizer:
  TapGestureRecognizer#02cb0
════════════════════════════════════════════════════════════════════════════════════════════════════

i dont know why this error occur and how to fix it, any help would mean so much to me.

here is my "HomePage" code

import 'package:flutter/material.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'Reminder/ui/home_reminder.dart';
import 'Reminder/ui/widgets/button.dart';

void main() {
  // debugPaintSizeEnabled = true;
  runApp(const HomePage());
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Medicine Reminder App'),
        ),
        body: Column(
          children: [
            Stack(
              children: [
                Image.asset(
                  'images/MenuImg.jpg',
                  width: 600,
                  height: 200,
                  fit: BoxFit.cover,
                ),
              ],
            ),
            const SizedBox(height: 10.0),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  child: const Text('Button 1'),
                  onPressed: () {
                     Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => const ReminderHomePage()),
                    );
                  },
                ),
                ElevatedButton(
                  child: const Text('Button 2'),
                  onPressed: () {},
                ),
                ElevatedButton(
                  child: const Text('Button 3'),
                  onPressed: () {},
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

and here is the "ReminderHomePage" that i want to navigate to

import 'package:date_picker_timeline/date_picker_timeline.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:medreminder/Reminder/services/notification_services.dart';
import 'package:medreminder/Reminder/services/theme_services.dart';
import 'package:intl/intl.dart';
import 'package:medreminder/Reminder/ui/theme.dart';
import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart';
import 'package:medreminder/Reminder/ui/widgets/button.dart';
import 'package:medreminder/Reminder/ui/widgets/add_remindbar.dart';
import 'package:medreminder/home_page.dart';

class ReminderHomePage extends StatefulWidget {
  const ReminderHomePage({super.key});

  @override
  State<ReminderHomePage> createState() => _ReminderHomePageState();
}

class _ReminderHomePageState extends State<ReminderHomePage> {
  DateTime _selectedDate = DateTime.now();
  var notifyHelper;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    notifyHelper=NotifyHelper();
    notifyHelper.initializeNotification();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _appBar(),
      backgroundColor: context.theme.backgroundColor,
      body: Column(
        children: [
          _addTaskBar(),
          _addDateBar(),
        ],
        ),
    );
  }
  _addDateBar(){
    return Container(
            margin: const EdgeInsets.only(top: 20, left: 20),
            child: DatePicker(
              DateTime.now(),
              height: 100,
              width: 80,
              initialSelectedDate: DateTime.now(),
              selectionColor: Color(0xFFAAB6FB),
              selectedTextColor: Colors.white,
              dateTextStyle: GoogleFonts.lato(
                textStyle: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w600,
                    color:Colors.grey
                ),
              ),
              dayTextStyle: GoogleFonts.lato(
                textStyle: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color:Colors.grey
                ),
              ),
              monthTextStyle: GoogleFonts.lato(
                textStyle: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color:Colors.grey
                ),
              ),
              onDateChange: (date){
                    _selectedDate=date;
              },
            ),
          );
  }
  _addTaskBar(){
    return Container(
            margin: const EdgeInsets.only(left: 20, right: 20, top: 5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  margin: const EdgeInsets.symmetric(horizontal: 20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(DateFormat.yMMMMd().format(DateTime.now()),
                      style: subHeadingStyle,
                      ),
                      Text("Today", 
                      style: headingStyle,
                      )
                    ],
                  ),
                ),
                MyButton(label: "Add Reminder", onTap: ()=>Get.to(AddReminderPage()))
              ],
            ),
          );
  }

  _appBar(){
    return AppBar(
      elevation: 0,
      backgroundColor: context.theme.backgroundColor,
      leading: GestureDetector(
        onTap: (){
            ThemeService().switchTheme();
            notifyHelper.displayNotification(
              title:"Theme Changed!",
              body: Get.isDarkMode?"Activated Light Theme!":"Activated Dark Theme!"
            );

            notifyHelper.scheduledNotification();
        },
        child: Icon(Get.isDarkMode ?Icons.wb_sunny_outlined:Icons.nightlight_round,
        size: 20,
          color:Get.isDarkMode ? Colors.white:Colors.black
        ),
      ),
      actions: [
        CircleAvatar(
          backgroundImage: AssetImage(
            "images/profile.png"
          ),
        ),
        // Icon(Icons.person,
        // size: 20,),
        SizedBox(width: 20,),
      ],
    );
  }
}

thankyou.

2

Answers


  1. Check this flutter site

    https://docs.flutter.dev/cookbook/navigation/navigation-basics

    For navigation use this

      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const ReminderHomePage()),
      );
    
    Login or Signup to reply.
  2. That’s not how you Navigate. You just need to give the class name in the builder method.

    From this:

    onPressed: () {
                         Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const Scaffold(
                              body: ReminderHomePage()
                            ),
                          ),
                        );
                      },
    

    To this:

    void main() {
      runApp(const MyApp()); //change the main method to call our root class
    }
    
    class MyApp extends StatelessWidget { //add a new class on top of your main class
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const HomePage(), //call your old class in that new main class
        );
      }
    

    And this should remain the same:

    onPressed: () {
                         Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const ReminderHomePage(),
                          ),
                        );
                      },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search