Search code examples
imageflutterappbar

Flutter : How to call a screen onclick on image of reusable appbar


I have created a reusable appBar class and calling it wherever i want to use here is the code



class MyAppBar extends AppBar {
  
 MyAppBar({Key key,Widget title})
   :super(key:key ,title:title,actions: <Widget>[
     InkWell(
        onTap: () {
          Profile();
            
        },
        child: Padding(
            padding: const EdgeInsets.all(14),
            child: ClipOval(
            
                child: Image.network(
                    'https://googleflutter.com/sample_image.jpg',
                ),
            ),
        ),
    ),
  
   ]
   );}


when click on image it is not redirecting to profile screen. i used this also

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

but it's giving me error on context as it's not define.

please help if anyone know how to fix it.


Solution

  • you can have the access of context inside a build function so do it like this, create a function variable inside you custom appbar and give it to InkWell like this,

    class MyAppBar extends AppBar {
    final Function onPressed;
    ...
    
    InkWell(
    onTap: onPressed,
    child:...
       )
     }
    

    now where you use the appbar pass that function there like this,

    Scaffold(
    appBar : MyAppBar(
    onPressed: (){
    Navigator.push(context, MaterialPageRoute(builder: (context)=>Profile()));
       },
    title: ...
     ),
    );