Search code examples
flutterappbar

Flutter: Navigate route for custom Appbar


A custom AppBar is created by error (error: Undefined name 'context') when adding navigation routes Below is the custom widget

Widget customAppBarTest(String title, bool backButton, bool home, bool about) {
  return AppBar(
    centerTitle: true,
    title: Center(
      child: Text(title),
    ),
    automaticallyImplyLeading: false,
    leading: GestureDetector(
        onTap: () {
          print('Go previous screen');
          Navigator.pop(context);
          //Navigator.of(context).pop();
        },
        child: const Icon(Icons.arrow_back)),
    actions: [
      GestureDetector(
          onTap: () {
            print('Go home');
/*            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const HomeMenu(),
              ),
            );*/
          },
          child: const Icon(Icons.home))
    ],
  );
}

I have no issue without using the default AppBar, but needs to use the customAppBarTest for easier code management


Solution

  • You should add BuildContext context parameter in that function

    Widget customAppBarTest(BuildContext context, String title, bool backButton, bool home, bool about) {
      return AppBar(
        centerTitle: true,
        title: Center(
          child: Text(title),
        ),
        automaticallyImplyLeading: false,
        leading: GestureDetector(
            onTap: () {
              print('Go previous screen');
              Navigator.pop(context);
              //Navigator.of(context).pop();
            },
            child: const Icon(Icons.arrow_back)),
        actions: [
          GestureDetector(
              onTap: () {
                print('Go home');
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const HomeMenu(),
                  ),
                );
              },
              child: const Icon(Icons.home))
        ],
      );
    }