In Flutter to create a toolbar we use the well-known AppBar widget, and when we want a dynamic toolbar that when we slide it shows us content, we use the great widget called SliverAppBar.

These Widgets allow us to add a touch of beauty to our application, and without a doubt, doing it in Flutter is very simple.

I have seen many questions in StackOverflow and Facebook groups about how we can modify the AppBar and SliverAppBar, modify in the sense of changing the behaviour or design a bit.

Let’s see these 2 cases.

Case 1

We want to create an AppBar that is not stuck at the top of the screen as we normally do. But we also want our screen to have a Drawer (side menu), and that our AppBar respond to the event of opening the Drawer. That is, we want to create our own AppBar, with the dimensions that we want.

The problem is that as we know, our AppBar widget has a default size, and we can not change it. Checking the source code, we see the parameter called appBar from the Scaffold, we see that it accepts a widget of type PreferredSizeWidget, now we review the source code of AppBar, and we find that it is only a StatefulWidget that implements PreferredSizeWidget.

We already have it, we will create our own Widget that implements PreferredSizeWidget.

What we want

How we do it so that when pressing the menu button of our AppBar the side menu opens.

We can do it in 2 ways:

Using the `AppBar` widget

With this the AppBar is responsible for opening the lateral menu if it is inside a Scaffold.

Using a Custom widget

With this we have more flexibility, to do it we can use GlobalKey of the type ScaffoldState or using the InheritedWidget of Scaffold, with that we have access to methods of the State with which we can open the Drawer.

Result

Simple, no? let’s see the second case with the SliverAppBar.

Case 2

We know that the SliverAppBar works in the following way:

But what we want is to put a Card embedded in our SliverAppBar as shown in the following image.

Wait, but the content that is inside the SliverAppBar is clipped so it can not exceed the constraints, and now what do we do?

Quiet, let’s see the source code of the SliverAppBar, oh surprise, it’s a StatefulWidget that uses a SliverPersistentHeader inside, that’s the secret.

We are going to create our own SliverPersistentHeaderDelegate in order to use the SliverPersistentHeader.

Result

Done, we already have our 2 cases resolved.

You can see the examples in the following repo.

Conclusion

Many times we get desperate when we do not find some Widget properties that Flutter provides, but it is always a good practice to check the source code of how the current Widgets are built to understand how Flutter works and the different options we have to create our own Widgets.

You can follow me on Twitter