0
votes

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'.

  • 'UserProfile' is from 'package:speedoo/pages/profilepage.dart' ('lib/pages/profilepage.dart'). Try correcting the name to the name of an existing getter, or defining a getter or field named 'context'. Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage()));
1
Share the error along with more code to give us context in where this getter is. Additionally, provide code that includes Navigator.push somewhere. The code you posted doesn't have Navigator.push anywhere.Christopher Moore
edited with errorWytex System

1 Answers

1
votes

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()));

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