Disable animation when changing tabs in Flutter

Viewed 5045

I have a tabbar with 3 tabs in flutter. When changing from first tab to the third tab also the initState method of tab2 is called. I don't want that.

import 'package:flutter/material.dart';

void main() {
  runApp(TabBarDemo());
}

class TabBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.directions_car)),
                Tab(icon: Icon(Icons.directions_transit)),
                Tab(icon: Icon(Icons.directions_bike)),
              ],
            ),
            title: Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}

When on tab1 and click on tab3 I want that tab3 is displayed immediately. Without animation.

4 Answers

Disable animation between flutter tabs by setting animation duration to zero like this

    tabController = TabController(
    animationDuration: Duration.zero); 

Thank me later!

I haven't tested this, but you could try setting a custom TabController to the TabBar and TabBarView, which overrides the animateTo method such that the animation is skipped:

class CustomTabController extends TabController {
  @override
  void animateTo(int value, {Duration duration = kTabScrollDuration, Curve curve = Curves.ease}) {
    super.animateTo(value, duration: null, curve: null);
  }
}

This is no animation TabController code. Please try it.

class NoAnimationTabController extends TabController {
  NoAnimationTabController(
      {int initialIndex = 0,
      @required int length,
      @required TickerProvider vsync})
      : super(initialIndex: initialIndex, length: length, vsync: vsync);

  @override
  void animateTo(int value,
      {Duration duration = kTabScrollDuration, Curve curve = Curves.ease}) {
    super.animateTo(value,
        duration: const Duration(milliseconds: 0), curve: curve);
  }
}
Related