Search code examples
flutternavigationappbar

Flutter own AppBar needs context with navigation


I made via a tutorial a own app bar with a gradient color. But now can I not navigate with the buttons to my settings view. The button needs a context. Can you help me how I fix this issue please? Thanks!

class MyAppBar extends AppBar {
  MyAppBar({Key key, Widget title}) 
  : super(
      key: key, 
      title: title, 
      centerTitle: true, 
      flexibleSpace: Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: <Color>[
          Color.fromRGBO(255, 120, 84, 1),
          Color.fromRGBO(236, 10, 131, 1)
        ])          
      )),  
      actions: <Widget>[
      new IconButton(
        icon: new Icon(Icons.notifications),
        onPressed: ()=> print("tap"),
      ),
      new IconButton(
        icon: new Icon(Icons.settings),
        onPressed: () => Navigator.pushReplacementNamed(context, Settings.id),
      )
  ]);
}

Solution

  • You need to extend a StatelessWidget to get your BuildContext and then implement PreferredSizeWidget because the AppBar itself implements it.

    class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
    final String screenTitle;
    
    MyAppBar({@required this.screenTitle});
    
    @override
    Widget build(BuildContext context) {
      return AppBar(
        title: Text(screenTitle),
        actions: // Whatever you need
      );
    }
    
    @override
    Size get preferredSize => Size.fromHeight(kToolbarHeight);
    }
    

    You also need to override get preferredSize and specify a height. In this example, I used a constant already specified by Flutter that is 56.0 for the toolbar component of the AppBar.