Wytex System
Wytex System

Reputation: 147

on flutter Widget without context cant use Navigator.push function on onPressed

If into a widget I try to use onPressed function Navigator.push it return error this is the code

  Widget get _navigationDrawer {
    return Container(
      height: 60.0,
      child: BottomAppBar(
        color: Color(0xFF1f2032),
        elevation: 35,
          shape: CircularNotchedRectangle(),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(right: 35),
                child: IconButton(
                  icon: Icon(Icons.settings,color: Colors.white,),
                  onPressed: () {
                    Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage()));

                  },
                ),
              ),
            ],
          )),
    );
  }

as you can see IconButton has onPressed function but if I add:

Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage()));

I got this error: Compiler message: lib/pages/profilepage.dart:62:36: Error: The getter 'context' isn't defined for the class 'UserProfile'.

Upvotes: 0

Views: 883

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17133

BuildContext isn't something that is globally available in a flutter app. UserProfile class is likely not a Widget(though I cannot tell as you haven't provided where this getter exists), and therefore doesn't automatically have access to context.

This can be easily solved by making this function not a getter, and making a BuildContext parameter. When you call this function, pass whatever context is available at that moment.

Widget _navigationDrawer(BuildContext context) {
    return Container(
      height: 60.0,
      child: BottomAppBar(
        color: Color(0xFF1f2032),
        elevation: 35,
          shape: CircularNotchedRectangle(),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(right: 35),
                child: IconButton(
                  icon: Icon(Icons.settings,color: Colors.white,),
                  onPressed: () {
                    Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage()));

                  },
                ),
              ),
            ],
          )),
    );
  }

Upvotes: 1

Related Questions