颤动 TabBarView 不会被 TabController 改变

use*_*654 5 flutter

我正在尝试以编程方式在应用程序内的选项卡之间进行更改。tabController.animateTo() 只改变 TabBar,而不改变 TabBarView。

这是我的示例,每当我向右滑动时,它应该 animateTo LEFT,因为选项卡更改侦听器会自动调用 animateTo(0)。但只有 TabBar 更改为 LEFT(如预期),而不是 TabBarView(未预期)。我希望两者都更改为 LEFT。

这是一个错误还是我错过了什么?

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),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

die*_*per 5

那是因为您在每次更改时都有一个侦听器,_tabController.addListener(_handleTabChange);并且每次调用时_tabController.animateTo_handleTabChange都会执行该方法,然后它只是动画到第一个选项卡。

删除或注释此行

 _tabController.addListener(_handleTabChange);
Run Code Online (Sandbox Code Playgroud)

它应该工作