codeName
codeName

Reputation: 121

Flutter.. How to implement a Custom App Bar - Usage and Re-Usage

I've created a Custom App Bar (CAB) for my Flutter mobile app that should appear at the top of every page. Right now the the entire code is copy/pasted on every page. But is there a way to create the CAB component once and place it as a self-contained component on each page, so that if i want to make a change to the CAB, i wont have to perform the same edit over and over on every page the CAB appears? Just trying to tidy things up a bit. Thanks!

Upvotes: 4

Views: 3743

Answers (1)

Ariel Lubaschewski
Ariel Lubaschewski

Reputation: 175

To make your Custom Appbar you need to 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.

Upvotes: 6

Related Questions