3

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!

codeName
  • 111
  • 1
  • 9
  • Yes, I suggest making a root folder to place any widgets you'd like to re-use throughout your app. In that folder you should have a file for your appBar, something like: `AppBar exampleAppBar(BuildContext context) {}` then wherever you want to use it, you can do so like : `return Scaffold( appBar: exampleAppBar(context),...` – Unbreachable Jun 24 '20 at 22:02
  • Hey man, there is a very nice and helpful article published in Medium - [check it here](https://medium.com/flutter-community/flutter-increase-the-power-of-your-appbar-sliverappbar-c4f67c4e076f) – vinipx Jun 24 '20 at 22:05
  • Thank you for the suggestion! i'll be researching this asap – codeName Jun 25 '20 at 00:45

1 Answers1

4

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.