4

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!

3
  • 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),... Commented Jun 24, 2020 at 22:02
  • Hey man, there is a very nice and helpful article published in Medium - check it here Commented Jun 24, 2020 at 22:05
  • Thank you for the suggestion! i'll be researching this asap Commented Jun 25, 2020 at 0:45

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

can support that the Size get preferredSize => Size.fromHeight(kToolbarHeight); works flawlessly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.