TabBar does not scroll to the correct tab after controller is changed

This issue has been created since 2022-11-23.

Steps to Reproduce

  1. Execute flutter run on the code sample
  2. Press the + button to increase the number of tabs

Expected results:
TabBar should scroll to the last tab but it does not, even though that becomes the selected tab as you can see by manually scrolling to the right

Actual results:
TabBar does not scroll to the correct tab

Code sample
import 'package:flutter/material.dart';

void main() => runApp(const TabBarNotScrollingHome());

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const TabBarNotScrollingAfterControllerChanged(),
    );
  }
}

class TabBarNotScrollingAfterControllerChanged extends StatefulWidget {
  const TabBarNotScrollingAfterControllerChanged({super.key});

  @override
  State<TabBarNotScrollingAfterControllerChanged> createState() =>
      _TabBarNotScrollingAfterControllerChangedState();
}

class _TabBarNotScrollingAfterControllerChangedState
    extends State<TabBarNotScrollingAfterControllerChanged>
    with TickerProviderStateMixin {
  final _scrollViewController = ScrollController(initialScrollOffset: 0.0);
  TabController? _tabController;
  late List<Widget> tabPages;
  bool increaseTabs = false;
  int _totalTabs = 10;
  TabBar? _tabBar;

  @override
  void initState() {
    super.initState();
    _generateTabs();
  }

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

  @override
  Widget build(BuildContext context) {
    final buildBody =
        TabBarView(controller: _tabController, children: tabPages);

    return Scaffold(
      body: NestedScrollView(
        controller: _scrollViewController,
        floatHeaderSlivers: true,
        headerSliverBuilder: buildAppBar,
        body: buildBody,
      ),
    );
  }

  List<Widget> buildAppBar(BuildContext context, bool isScrolled) {
    final addButton = IconButton(
      icon: Icon(increaseTabs ? Icons.remove : Icons.add),
      onPressed: () {
        increaseTabs = !increaseTabs;
        _generateTabs();
        setState(() {});
      },
    );

    return <Widget>[
      SliverAppBar(
        title: const Text('Press + to increase tabs =>'),
        bottom: _tabBar,
        pinned: true,
        snap: false,
        primary: true,
        actions: [addButton],
      ),
    ];
  }

  void _generateTabs() {
    if (increaseTabs) {
      _totalTabs = 15;
    } else {
      _totalTabs = 10;
    }
    _tabController = TabController(
        vsync: this, length: _totalTabs, initialIndex: _totalTabs - 1);

    _tabBar = TabBar(
      tabs: List.generate(
          _totalTabs, (index) => Center(child: Tab(text: 'Tab $index'))),
      controller: _tabController,
      isScrollable: true,
    );

    tabPages = List.generate(
      _totalTabs,
      (index) => Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Page $index', textAlign: TextAlign.center),
            const SizedBox(height: 20),
            const Text(
              'After pressing the + button to increase the tabs this page '
              'will change but the tab above will not scroll to the last Tab '
              'even though that becomes the selected tab. However if you press '
              'again to decrease the tabs it will scroll to the new last tab',
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.red),
            ),
          ],
        ),
      ),
    );
  }
}
Logs
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 3.3.8, on Microsoft Windows [Version 10.0.19045.2251], locale en-US)
Checking Android licenses is taking an unexpectedly long time...[√] Android toolchain - develop for Android devices (Android SDK version 32.0.0-rc1)
[√] Chrome - develop for the web
[X] Visual Studio - develop for Windows
    X Visual Studio not installed; this is necessary for Windows development.
      Download at https://visualstudio.microsoft.com/downloads/.
      Please install the "Desktop development with C++" workload, including all of its default components
[√] Android Studio (version 2021.3)
[√] IntelliJ IDEA Ultimate Edition (version 2021.1)
[√] Connected device (4 available)
[√] HTTP Host Availability

TabBarIssue.mp4
absar wrote this answer on 2022-11-23
bleroux wrote this answer on 2022-11-23

@absar
Thanks for the detailed report.

I wonder if this case have been fixed by the following PR: #112168.
This PR is only on master channel, can you try to repro this on master channel?

Another question, is the issue still reproducible if you remove the NestedScrollView?

absar wrote this answer on 2022-11-23

@bleroux
Same issue on Flutter Channel master 3.6.0-7.0.pre.39.
There is no relation to NestedScrollView, issue persists without NestedScrollView, code without it appended below

Code without NestedScrollView
import 'package:flutter/material.dart';

void main() => runApp(const TabBarNotScrollingHome());

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const TabBarNotScrollingAfterControllerChanged(),
    );
  }
}

class TabBarNotScrollingAfterControllerChanged extends StatefulWidget {
  const TabBarNotScrollingAfterControllerChanged({super.key});

  @override
  State<TabBarNotScrollingAfterControllerChanged> createState() =>
      _TabBarNotScrollingAfterControllerChangedState();
}

class _TabBarNotScrollingAfterControllerChangedState
    extends State<TabBarNotScrollingAfterControllerChanged>
    with TickerProviderStateMixin {
  TabController? _tabController;
  late List<Widget> tabPages;
  bool increaseTabs = false;
  int _totalTabs = 10;
  TabBar? _tabBar;

  @override
  void initState() {
    super.initState();
    _generateTabs();
  }

  @override
  void dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final buildBody =
        TabBarView(controller: _tabController, children: tabPages);

    final addButton = IconButton(
      icon: Icon(increaseTabs ? Icons.remove : Icons.add),
      onPressed: () {
        increaseTabs = !increaseTabs;
        _generateTabs();
        setState(() {});
      },
    );

    final buildAppBar = AppBar(
      title: const Text('Press + to increase tabs =>'),
      bottom: _tabBar,
      primary: true,
      actions: [addButton],
    );

    return Scaffold(appBar: buildAppBar, body: buildBody);
  }

  void _generateTabs() {
    if (increaseTabs) {
      _totalTabs = 15;
    } else {
      _totalTabs = 10;
    }
    _tabController = TabController(
        vsync: this, length: _totalTabs, initialIndex: _totalTabs - 1);

    _tabBar = TabBar(
      tabs: List.generate(
          _totalTabs, (index) => Center(child: Tab(text: 'Tab $index'))),
      controller: _tabController,
      isScrollable: true,
    );

    tabPages = List.generate(
      _totalTabs,
      (index) => Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Page $index', textAlign: TextAlign.center),
            const SizedBox(height: 20),
            const Text(
              'After pressing the + button to increase the tabs this page '
              'will change but the tab above will not scroll to the last Tab '
              'even though that becomes the selected tab. However if you press '
              'again to decrease the tabs it will scroll to the new last tab',
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.red),
            ),
          ],
        ),
      ),
    );
  }
}

danagbemava-nc wrote this answer on 2022-11-24

The issue is reproducible using the code sample provided in #115917 (comment).

recording
Simulator.Screen.Recording.-.iPhone.14.Pro.-.2022-11-24.at.06.05.40.mp4
flutter doctor -v
[✓] Flutter (Channel stable, 3.3.8, on macOS 13.0.1 22A400 darwin-arm, locale en-GB)
    • Flutter version 3.3.8 on channel stable at /Users/nexus/dev/sdks/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 52b3dc25f6 (2 weeks ago), 2022-11-09 12:09:26 +0800
    • Engine revision 857bd6b74c
    • Dart version 2.18.4
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/nexus/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/213.7172.25.2113.9123335/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14B47b
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[!] Android Studio
    • Android Studio at /Applications/Android Studio Preview.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    ✗ Unable to find bundled Java version.
    • Try updating or re-installing Android Studio.

[✓] Android Studio (version 2021.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[!] Android Studio
    • Android Studio at /Applications/Android Studio Preview 2.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    ✗ Unable to find bundled Java version.
    • Try updating or re-installing Android Studio.

[✓] Android Studio (version 2021.3)
    • Android Studio at /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/213.7172.25.2113.9123335/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] Android Studio (version 2021.3)
    • Android Studio at /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/213.7172.25.2113.9014738/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] VS Code (version 1.73.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.52.0

[✓] Connected device (3 available)
    • iPhone 14 Pro (mobile) • 4F72110C-F38B-4CF9-93C4-4D6042148D28 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-1 (simulator)
    • macOS (desktop)        • macos                                • darwin-arm64   • macOS 13.0.1 22A400 darwin-arm
    • Chrome (web)           • chrome                               • web-javascript • Google Chrome 107.0.5304.110

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 2 categories.
[!] Flutter (Channel master, 3.6.0-7.0.pre.45, on macOS 13.0.1 22A400 darwin-arm64, locale en-GB)
    • Flutter version 3.6.0-7.0.pre.45 on channel master at /Users/nexus/dev/sdks/flutters
    ! Warning: `flutter` on your path resolves to /Users/nexus/dev/sdks/flutter/bin/flutter, which is not inside your current Flutter SDK checkout at /Users/nexus/dev/sdks/flutters. Consider adding /Users/nexus/dev/sdks/flutters/bin to the front of your path.
    ! Warning: `dart` on your path resolves to /Users/nexus/dev/sdks/flutter/bin/dart, which is not inside your current Flutter SDK checkout at /Users/nexus/dev/sdks/flutters. Consider adding /Users/nexus/dev/sdks/flutters/bin to the front of your path.
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision d0352f55db (5 hours ago), 2022-11-23 20:01:26 -0500
    • Engine revision 9b2895724c
    • Dart version 2.19.0 (build 2.19.0-424.0.dev)
    • DevTools version 2.19.0
    • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades.

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/nexus/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/213.7172.25.2113.9123335/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14B47b
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[!] Android Studio
    • Android Studio at /Applications/Android Studio Preview.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    ✗ Unable to find bundled Java version.
    • Try updating or re-installing Android Studio.

[✓] Android Studio (version 2021.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[!] Android Studio
    • Android Studio at /Applications/Android Studio Preview 2.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    ✗ Unable to find bundled Java version.
    • Try updating or re-installing Android Studio.

[✓] Android Studio (version 2021.3)
    • Android Studio at /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/213.7172.25.2113.9123335/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] Android Studio (version 2021.3)
    • Android Studio at /Users/nexus/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/213.7172.25.2113.9014738/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] VS Code (version 1.73.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.52.0

[✓] Connected device (3 available)
    • iPhone 14 Pro (mobile) • 4F72110C-F38B-4CF9-93C4-4D6042148D28 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-1 (simulator)
    • macOS (desktop)        • macos                                • darwin-arm64   • macOS 13.0.1 22A400 darwin-arm64
    • Chrome (web)           • chrome                               • web-javascript • Google Chrome 107.0.5304.110

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 3 categories.
bleroux wrote this answer on 2022-11-25

@absar Many thanks for pointing out this issue and for the great repro.
I filed a PR for this issue: #116019.

@TahaTesser noticed that there is a duplicate (#96718).
I will close this one as a duplicate, thank you to follow up on #96718.

More Details About Repo
Owner Name flutter
Repo Name flutter
Full Name flutter/flutter
Language Dart
Created Date 2015-03-06
Updated Date 2022-12-10
Star Count 147243
Watcher Count 3561
Fork Count 23950
Issue Count 11325

YOU MAY BE INTERESTED

Issue Title Created Date Comment Count Updated Date
gzip: stdin: not in gzip format 1 2021-03-31 2022-12-09
Option to set key expiration on generate 1 2021-08-30 2022-09-10
Potential new BA.5.X lineage in Asturias (mainly) 20 2022-05-10 2022-10-26
Off-topic: BTC Mouse & Trackpad IOS 10+ 30 2017-03-29 2022-11-02
Additional things we can do to check the validity of the index chunks 0 2022-08-26 2022-09-11
V1.0 - Include config information in the chunk header of each chunk 0 2022-08-26 2022-09-11
Windows compilation failure 6 2021-10-09 2022-11-15
cpp_comment example in playground is incomplete 2 2021-12-11 2022-11-15
Can't install crow-translate on Fedora 36 (libtesseract.so.4()) 12 2022-05-12 2022-11-26
Adding call to page.screenshot triggers a failure 1 2021-05-12 2022-10-27
progress doesnt update on new documents 3 2021-01-15 2022-11-18
Content Overflow in Editor Seciton 0 2021-06-02 2022-11-17
Unable to deploy more than one cluster with Operator 4 2021-07-20 2022-11-05
BUG: pasting a whole HTML page 1 2022-09-21 2022-12-01
New Docker Container with imbedded flows throws error when loading while parsing directory 3 2022-08-31 2022-08-31
Deployments using docker infrastructure with base Prefect image cannot use github storage 0 2022-08-31 2022-08-31
Github storage requires flow to be importable from root directory 0 2022-08-31 2022-08-31
PragmaExpr erroneously added to enum type 0 2021-10-18 2022-08-07
Issues with a clean pip install of intelmq on RHEL 8 5 2021-09-27 2022-07-25
udp转发出现recv queue is full 4 2020-11-29 2022-09-19
Breaking changes for massiv-1.0 release 1 2020-07-28 2022-11-03
Possible False Positive for CVE-2016-1000027 1 2022-08-16 2022-12-06
Crashing from non-loaded VSTs 2 2021-10-11 2022-11-09
Conflicting information in 2 articles. 1 2022-02-27 2022-10-07
Webpack plugin broken in Next.js v10.0.6 1 2021-01-31 2022-11-21
Align attribute categories with GC? 3 2021-12-28 2022-11-29
[Bug] [Windows] check_quiesce_snapshot failed due to test_pre_freeze.txt not exist 2 2021-08-20 2022-10-16
Lyrics won't show anymore 0 2022-09-29 2022-12-01
Tests are relying on undefined interceptors order 5 2021-08-27 2022-12-08
golint is obsolete 1 2021-08-18 2022-01-16
Fix strange behaviour in ui editor 0 2022-11-11 2022-11-24
Links resolving to file paths on org-roam-insert 2 2022-03-17 2022-10-31
Query error in Machine Learning examples notebook 1 2022-07-01 2022-12-02
about:config is blocked on Firefox Focus Beta for Android 1 2022-01-12 2022-01-21
www.wavve.com 40 2021-11-03 2022-01-13
Change frequency of updating GeoDB from 0:20UTC to every 12 hours 0 2021-03-06 2022-10-16
[Feature Request]: Rounded Windows when transparent is set to True on Win11 0 2021-12-28 2022-10-08
No delegateCommandHandler for vscode.java.startDebugSession when starting Debugger in Gitpod 7 2021-11-24 2022-12-09
[proposal] consider renaming the project 0 2021-02-18 2022-12-01
CI updates - add static analysis and format in workflow 0 2021-02-01 2022-10-11
EKS Test Migration - jakemulley-cloud-platform-dev 2 2021-09-20 2022-10-18
Spell check on website 1 2022-09-07 2022-12-05
direction option does not work 1 2022-08-26 2022-12-02
Hide ACF Menu 7 2018-06-04 2022-01-19
Unable to deploy to Hololens 2 from CLI 3 2021-05-26 2022-07-17
"Load More Stack Frames" is incorrectly displayed after debug adapter has sent the full stack 1 2022-10-29 2022-10-31
Terraform changes for Automate HA based on EAP feedback 1 2022-01-20 2022-11-20
props 传递参数为动态时,使用 sync 标记也不能获取最新数据 18 2018-01-14 2022-12-05
Possible memory leak MockMethodDispatcher 3 2021-12-08 2022-10-20
`impellerc` and `libtessellator` should run natively on Apple Silicon arm machines 6 2022-08-19 2022-12-03