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(); } }
ScrollController _scrollViewController; bool _showAppbar = true; bool isScrollingDown = false;
@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(() {}); } } }); }
@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.
…
Leave A Comment