Custom Gradient AppBar in flutter, a much-asked requirement, in the most proper way

Rahul Dev
2 min readDec 7, 2022

--

Goal : If you are working with an UI person there is a high chance that UI fellow came up with an AppBar design with custom gradient AppBar design, thats why you are here.

Most of you only need sample code to implement this, you may be able to understand yourself, so let's start with code directly

import 'package:flutter/material.dart';

class GradientAppBar extends StatelessWidget implements PreferredSizeWidget {
const GradientAppBar({
Key? key,
this.title,
this.actions,
}) : super(key: key);

final Widget? title;
final List<Widget>? actions;

@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);

@override
Widget build(BuildContext context) {
return AppBar(
flexibleSpace: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xFF018786),
Color(0xFF03DAC6),
],
),
),
),
title: title,
actions: actions,
);
}
}

If you understood the code and fulfilled the requirement, you can skip the rest of the story.

Now, breakdown the code and understand piece by piece,

appBar expects PreferredSizeWidget?

Inside the scaffold, the property appBar asks for PreferredSizeWidget, and it will not accept StatelessWidget. So, we need to make a widget that extends or implements PreferredSizeWidget,

That’s why in the above code, GradientAppBar class implements PreferredSizeWidget.

class GradientAppBar extends StatelessWidget implements PreferredSizeWidget{}

As soon as you implement PreferredSizeWidget, it will tell you to

@override
Size get preferredSize

You can use the default of flutter as below,

@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);

Make appBar background gradient

It is actually very easy, AppBar class has a property called flexibleSpace, you need to assign a container with a gradient background to that and with no height, width, or also no child to that. Like below,

@override
Widget build(BuildContext context) {
return AppBar(
flexibleSpace: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xFF018786),
Color(0xFF03DAC6),
],
),
),
),
title: title,
actions: actions,
);
}

I have used only LinearGradient above as an example, but you can set any other Gradient class.

Wanna try above code running ?? You can run the code in the following link in dartpad online editor. Click below to go to dartpad.

Output of above code is like below

There are another much asked requirement is Custom Gradient Button, That we will discuss How to do that in most proper way, in another post. Stay tuned.

--

--

Rahul Dev

Software Engineering Specialist at BT Group ◇ Ex-SSE at LendingKart, Mantra Labs