Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 73 ยท Material, styling and assets

Tabs: TabBar, TabBarView and PageView

Build tabbed screens in Flutter with DefaultTabController, TabBar and TabBarView, swipe between pages with PageView, keep tab state alive, and build carousels.

Tabs let people move between sibling views of the same level without a back button: "All, Unread, Starred" in a mail app, or "Today, Week, Month" in a chart screen. Flutter splits the idea into two cooperating widgets. A TabBar is the row of labels, and a TabBarView is the area of pages beneath it. A TabController keeps the two in sync, so tapping a label slides the page and swiping the page moves the label's indicator.

The same sliding-page machinery sits one level lower in PageView, which you use for onboarding screens, photo galleries and carousels where no label row is needed. This lesson covers both.

Real vs stand-in. The Dart code is real Flutter and read-only here, because the site cannot run a Flutter app. The live examples are JavaScript stand-ins of the logic underneath: the controller's index rules, the page snapping math, and the lifetime of a tab's state.

The shortest tab screen

DefaultTabController creates a TabController for you and shares it with every TabBar and TabBarView below it. The only thing you must supply is length, and it has to match the number of tabs and the number of pages.

DART
class InboxScreen extends StatelessWidget {
  const InboxScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Inbox'),
          bottom: const TabBar(
            tabs: [
              Tab(text: 'All', icon: Icon(Icons.inbox)),
              Tab(text: 'Unread', icon: Icon(Icons.mark_email_unread)),
              Tab(text: 'Starred', icon: Icon(Icons.star)),
            ],
          ),
        ),
        body: const TabBarView(
          children: [
            MessageList(filter: Filter.all),
            MessageList(filter: Filter.unread),
            MessageList(filter: Filter.starred),
          ],
        ),
      ),
    );
  }
}

TabBar goes in AppBar.bottom (or anywhere else; it only needs a height). If length and the child counts disagree, Flutter throws a clear assertion about the controller's length. A Tab may hold text, an icon, a custom child, or a combination.

Styling the bar

Most looks are one property away:

Property What it does
isScrollable: true Tabs take their natural width and the bar scrolls. Use it for more than four or five tabs.
tabAlignment TabAlignment.start or center for scrollable bars, fill for fixed ones.
indicatorSize TabBarIndicatorSize.tab (full tab width) or label (text width).
labelColor, unselectedLabelColor Colors of the selected and other labels.
indicator A custom Decoration, for example a pill with BoxDecoration.
dividerColor Color of the line under the bar in Material 3.

Set defaults for the whole app with TabBarTheme inside your ThemeData instead of repeating them. Material 3 also offers TabBar.secondary, a quieter variant for tabs nested inside a page that already has a primary bar.

Controlling tabs from code

DefaultTabController.of(context) finds the shared controller. For anything beyond a plain screen, such as reacting to tab changes or jumping to a tab, own the controller yourself. It needs a TickerProvider for its slide animation, which is why the state class mixes in SingleTickerProviderStateMixin (see explicit animations).

DART
class _ReportsState extends State<Reports> with SingleTickerProviderStateMixin {
  late final TabController _tabs = TabController(length: 3, vsync: this)
    ..addListener(() {
      if (!_tabs.indexIsChanging) {
        debugPrint('now on tab ${_tabs.index}');
      }
    });

  @override
  void dispose() {
    _tabs.dispose();
    super.dispose();
  }

  void _jumpToWeek() => _tabs.animateTo(1);   // slide to the second tab

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TabBar(controller: _tabs, tabs: const [Tab(text: 'Today'), Tab(text: 'Week'), Tab(text: 'Month')]),
        Expanded(
          child: TabBarView(controller: _tabs, children: const [TodayView(), WeekView(), MonthView()]),
        ),
      ],
    );
  }
}

The listener fires several times during one swipe. indexIsChanging is true while the animation toward a tapped tab runs, so checking !indexIsChanging reacts once, after arrival. The controller also exposes previousIndex and offset, a fractional position useful for fading things during a drag.

Stand-in: the controller's rules

JS TabController: index, animateTo and clamping

Press Run (or Ctrl + Enter) to see the console output here.

No output.

PageView: swipeable pages without tabs

PageView is a scrolling list whose children each fill the viewport and snap into place. A PageController reads and drives the position.

DART
final controller = PageController(viewportFraction: 0.85);

PageView.builder(
  controller: controller,
  itemCount: photos.length,
  onPageChanged: (i) => setState(() => _current = i),
  itemBuilder: (context, i) => Padding(
    padding: const EdgeInsets.symmetric(horizontal: 6),
    child: ClipRRect(
      borderRadius: BorderRadius.circular(16),
      child: Image.asset(photos[i], fit: BoxFit.cover),
    ),
  ),
)

viewportFraction below 1 lets the neighbouring pages peek in, which is the classic carousel look. Use scrollDirection: Axis.vertical for story-style paging, physics: const NeverScrollableScrollPhysics() to allow only programmatic changes (a wizard with a "Next" button), and controller.animateToPage(2, duration: ..., curve: ...) to move by code. Draw a dot indicator from _current, or use a package such as smooth_page_indicator. Dispose the controller like any other.

For a ready-made carousel with sizing rules for each item, newer Flutter versions include CarouselView, which takes an itemExtent and a list of children. PageView stays the right tool when each item is a full screen.

JS PageView snapping with viewportFraction

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Keeping each tab's state alive

TabBarView builds a page lazily and may throw away pages that are far from the visible one, so a scroll position, a half-typed text field or a loaded list can vanish when you swipe away and back. To keep a page's State alive, mix AutomaticKeepAliveClientMixin into its state:

DART
class _FeedState extends State<Feed> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);   // required: registers the keep-alive request
    return ListView.builder(/* ... */);
  }
}

The super.build(context) call is the part everyone forgets. Another route is to hoist the state above the tabs (lifting state up) so rebuilding a page does not lose data. Do not keep every tab alive by default: each one holds its whole widget subtree in memory. The same mixin works for PageView children.

JS When is a tab's state discarded?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Mismatched counts. length: 3 with two pages fails at runtime. Build both lists from the same data to avoid it.
  • Forgetting dispose on a hand-made controller. Leaks the ticker.
  • A TabBarView without a bounded height. Inside a Column, wrap it in Expanded (constraints).
  • Nesting PageView inside a horizontal TabBarView. The two fight for the same swipe, so give the inner one a different axis or turn its scrolling off.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does DefaultTabController save you from writing?

    It creates a TabController from length, shares it with the TabBar and TabBarView beneath it, and disposes it.
  2. 2. Why do you call super.build(context) in a state that uses AutomaticKeepAliveClientMixin?

    The mixin's build method sends the keep-alive notification. Without the call, wantKeepAlive has no effect.
  3. 3. Which setting makes the neighbouring pages of a PageView peek in at the edges?

    A viewportFraction such as 0.85 makes each page narrower than the viewport, so the next and previous pages are partly visible.
  4. 4. A TabController needs a TickerProvider. How does a State class usually supply one?

    The mixin makes the State a TickerProvider, and vsync: this hands it to the controller for its slide animation.

Summary

  • TabBar shows the labels, TabBarView shows the pages, and a TabController keeps them in sync; DefaultTabController creates one for you.
  • Own the controller (with a ticker mixin and dispose) when you need animateTo, listeners or previousIndex.
  • PageView and PageController give swipeable full-page layouts; viewportFraction turns them into carousels.
  • Use AutomaticKeepAliveClientMixin sparingly to keep a page's state when it scrolls away.

Next: ExpansionTile, Stepper, DataTable and Table