user987654
user987654

Reputation: 6031

flutter TabBarView doesn't change by TabController

I'm trying to programmatically change between tabs inside the app. tabController.animateTo() only change the TabBar, but not TabBarView.

Here's my example, and it should animateTo LEFT whenever I swipe to the RIGHT because the tab change listener automatically call animateTo(0). But only the TabBar changes to LEFT (as expected), not the TabBarView (not expected). I want both change to LEFT.

Is this a bug or am I missing something?

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyTabbedPage(),
    );
  }
}

class MyTabbedPage extends StatefulWidget {
  const MyTabbedPage({Key key}) : super(key: key);

  @override
  _MyTabbedPageState createState() => new _MyTabbedPageState();
}

class _MyTabbedPageState extends State<MyTabbedPage> with SingleTickerProviderStateMixin {
  final List<Tab> myTabs = <Tab>[
    new Tab(text: 'LEFT'),
    new Tab(text: 'RIGHT'),
  ];

  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: myTabs.length);
    _tabController.addListener(_handleTabChange);
  }

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

  void _handleTabChange() {
    _tabController.animateTo(0);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Tab demo"),
        bottom: new TabBar(
          controller: _tabController,
          tabs: myTabs,
        ),
      ),
      body: new TabBarView(
        controller: _tabController,
        children: myTabs.map((Tab tab) {
          return new Center(child: new Text(tab.text));
        }).toList(),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: () => _tabController.animateTo((_tabController.index + 1) % 2), // Switch tabs
        child: new Icon(Icons.swap_horiz),
      ),
    );
  }
}

enter image description here

Upvotes: 6

Views: 7927

Answers (1)

diegoveloper
diegoveloper

Reputation: 103551

That's because you have a listener on every change _tabController.addListener(_handleTabChange); and every time you call _tabController.animateTo , the method _handleTabChange is executed then it just animate to the first tab.

Remove or comment this line

 _tabController.addListener(_handleTabChange);

And it should work

Upvotes: 6

Related Questions