[Solved] i am having a problem in page navigation while using drawer and bottom navigation

Question

Asked by Chandrasekar C on January 05, 2022 (source).

I am new to flutter I have tried to create bottom navigation and drawer I am getting an error while andding onTap function in drawer list tile the app works as expected but when I try to open drawer flutter gives an error

import 'package:flutter/material.dart';
import 'package:navigation_examples_meals/screen/categories_screen.dart';
import 'package:navigation_examples_meals/screen/filters_screen.dart';

class CustomDrawer extends StatelessWidget {
  
  Widget buildListTile(String title, IconData icon,Function onpressed){
    return ListTile(
        leading: Icon(
          icon,
          size: 26,
        ),
        title: Text(
          title,
          style:const TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.black,
            fontSize: 28,
          )
        ),
       
       onTap: onpressed(),
      );
  }  
  
  const CustomDrawer({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Column(children: <Widget>[
        Container(
          height: 120,
          width: double.infinity,
          padding:const EdgeInsets.all(20),
          alignment: Alignment.centerLeft,
          color: Colors.blue, 
           child:const Text(
            "We have what you need",
            style: TextStyle(
              fontWeight: FontWeight.w900,
              color:Colors.black,
              fontSize:25,
            )
          ),
        ),
        buildListTile(
          "Meals",Icons.restaurant,
          () {
            
          Navigator.of(context).pushReplacementNamed(FiltersScreen.routename);
          }
          ),
        buildListTile(
          "Filters", Icons.filter,
          () {
           Navigator.of(context).pushReplacementNamed(FiltersScreen.routename);
               }
          ),
      ],),
      
    );
  }
}

If i comment out the navigation the app works perfectly

class BottomNavigation extends StatefulWidget {
  
  const BottomNavigation({ Key? key }) : super(key: key);

  @override
  _BottomNavigationState createState() => _BottomNavigationState();
}

class _BottomNavigationState extends State<BottomNavigation> {
  final List<Map<String,dynamic>> pages = [
    {
    'page': CategoriesScreen(),
    'title': "Meals"
    },
    {
      'page': FavouritesScreen(),
      'title': "Favourites"
    },

  ];
  int selectedPage_Index = 0;
  void selectPage(int index){
    WidgetsBinding.instance!
        .addPostFrameCallback((_) => setState(() {
      selectedPage_Index = index;
    }));
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          pages[selectedPage_Index]['title'],
          style:const TextStyle(
            color: Colors.white,
          ),
        ),
        backgroundColor: Colors.blue,
      ),      
      
      drawer: CustomDrawer(),
      body: pages[selectedPage_Index]['page'],
      bottomNavigationBar: BottomNavigationBar(
        onTap: selectPage,
        unselectedItemColor: Colors.white,
        selectedItemColor: Colors.red,
        currentIndex: selectedPage_Index,
       // type: BottomNavigationBarType.shifting,
        backgroundColor: Colors.blue,
        items:const [
          BottomNavigationBarItem(
            icon:Icon(Icons.category),
            label: "Categories"  ,
            ),
            BottomNavigationBarItem(
              icon:Icon(Icons.star_border),
              label: "Favourites"  ,
            ),
        ],
      ),
    );
  }
}

this is my bottom navigation class

FlutterError (setState() or markNeedsBuild() called during build.
This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets.  A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was:
  Overlay-[LabeledGlobalKey<OverlayState>#0ca13]
The widget which was currently being built when the offending call was made was:
  CustomDrawer)

and this is my error

Answer

Question answered by Bach (source).

If you place the callback like this: onTap: onpressed(), it will instantly call the onpressed function during the widget rendering, thus the error.
You can rewrite it like this onTap: onpressed so the function is called only when you press the tile

Video Answers on YouTube

DART FLUTTER
SHARE: