Sitemap

Flutter — Sync TabBar with widget scroll

2 min readApr 4, 2023

--

Press enter or click to view image in full size

The final result:

To accomplish our goal, we’re going to use the following things:

  1. GlobalKey
  2. Scrollable.ensureVisibility()
  3. VisibilityDetector

First, we need to prepare our tabs data. As you can see, I make a list of tab items, with each contains it’s GlobalKey and label.

Then we can call Scrollable.ensureVisible() in the onTap callback (I’m using TabBar widget).

Get QK Er’s stories in your inbox

Join Medium for free to get updates from this writer.

We can use the GlobalKey we created just now to get the target widget context.

Lastly, we build our content widgets inside a list, where the list is build from another list of widget. You can look at the screenshot below.

Press enter or click to view image in full size

Then in the “outer” list, I’m using SingleChildScrollView, and wrap each “inner” list, the ListGroup inside VisibilityDetector.

To sync TabBar scroll with current category content, I use the data provided by onVisibilityChanged callback to determine whether the content is occupied half the screen.

You’re done!

Some of you may wonder why not using ListView.builder or SliverList to build the widgets lazily, the reason behind this is to make Scrollable.ensureVisible() works properly, otherwise it can’t find the correct context if the widget is not available yet, and there’s no way to do it currently XD.

--

--