π Yo!
A couple of days, I was building a simple app that takes data from an API and displays them on the screen. A simple app though.
Then I needed to add some height to my appBar. Well you might suggest
...
toolbarHeight: 100.0,
title: Text('Yo! Title here'),
...
but what if I want to customize my title, add some color, and use the properties across other screens well I don't want to go through the ctrl c & ctrl v
kinds of stuff.
Here is what I did
- Created a widget directory inside my lib folder
- Created a new custom_appBar.dart file
import 'package:flutter/material.dart';
class MyAppbar extends StatelessWidget with PreferredSizeWidget {
@override
final String title;
final Size preferredSize;
MyAppbar(this.title, {Key key})
: preferredSize = Size.fromHeight(100.0),
super(key: key);
@override
Widget build(BuildContext context) {
return AppBar(
title: Text(title,
style: TextStyle(color: Colors.white)
),
backgroundColor: Colors.white38,
);
}
}
My new MyAppbar
class extend the statelessWidget
. you also noticed I have with PreferredSizeWidget
right? Yea! this is because the Scaffold takes in a PreferredSizeWidget and not the AppBar class directly.
Then I set my constructor like so
...
MyAppbar(this.title, {Key key})
: preferredSize = Size.fromHeight(100.0),
super(key: key);
...
Lastly, my build method returns the AppBar class and there I can now set my AppBar properties
Now I can import and reuse my newly customized MyAppbar everywhere on my app
...
appBar: MyAppbar('Title goes here!'),
...
I also recommend checking this medium article too π
Top comments (0)