DEV Community

Oluwatobiloba
Oluwatobiloba

Posted on

Creating a Custom appBar

😜 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'),
...
Enter fullscreen mode Exit fullscreen mode

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

  1. Created a widget directory inside my lib folder
  2. 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,
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

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);
...
Enter fullscreen mode Exit fullscreen mode

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!'),
...
Enter fullscreen mode Exit fullscreen mode

I also recommend checking this medium article too πŸ‘

#dart

On the language, SDK and ecosystem.

Top comments (0)