Flutter — Hide / show AppBar while scrolling

Zeba Rahman
fabcoding
Published in
2 min readAug 3, 2020

Showing the AppBar as soon as you begin scrolling upward

The SliverAppBar provided by Flutter, supports a floating app bar that hides upon scrolling down. But there’s one downside about it, it reappears only when the user scrolls back up all way to the top of the scroll view. This can be undesirable if the scroll content happens to be larger. For example in the Medium app, the app bar shows up as soon as you start scrolling upward, no matter where you are. This is what we want.

So in this tutorial we will implement this action using ScrollController and AnimatedContainer.

Let us begin by creating a simple screen, a stateful widget.

class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Container();
}
}

Inside the state class, declare a scroll controller; and two variables to hold the current action/state.

ScrollController _scrollViewController;
bool _showAppbar = true;
bool isScrollingDown = false;

In the state initialization method, arrach a listener to the ScrollController and define its action to detect the scroll direction and accordingly set the value of the variable which will be used to determine the visibility of the app bar.

@override
void initState() {
super.initState();
_scrollViewController = new ScrollController();
_scrollViewController.addListener(() {
if (_scrollViewController.position.userScrollDirection == ScrollDirection.reverse) {
if (!isScrollingDown) {
isScrollingDown = true;
_showAppbar = false;
setState(() {});
}
}

if (_scrollViewController.position.userScrollDirection == ScrollDirection.forward) {
if (isScrollingDown) {
isScrollingDown = false;
_showAppbar = true;
setState(() {});
}
}
});
}

Don’t forget to dispose the controller!

@override
void dispose() {
_scrollViewController.dispose();
_scrollViewController.removeListener(() {});
super.dispose();
}

Now create the screen view in the build method.

@override
Widget build(BuildContext context) {

return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
AnimatedContainer(
height: _showAppbar ? 56.0 : 0.0,
duration: Duration(milliseconds: 200),
child: AppBar(
title: Text('Scroll Demo'),
actions: <Widget>[
//add buttons here
],
),
),

Expanded(
child: SingleChildScrollView(
controller: _scrollViewController,
child: Column(
children: <Widget>[
//add your screen content here
],
),
),
),

],
),
),
);
}

As you can see, our screen is a simple Column widget, with the AppBar wrapped in an AnimatedCnotainer, and a SingleChildScrollView in the rest of the area.

The AppBar is wrapped in AnimatedContainer in order to animate the hide and show transitions.

Originally published at Fabcoding.

--

--