本文介绍了TabController不会改变Flutter TabBarView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式在应用程序内的各个标签之间进行更改.tabController.animateTo()仅更改TabBar,而不更改TabBarView.

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

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

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),
      ),
    );
  }
}

推荐答案

这是因为您对每个更改_tabController.addListener(_handleTabChange);都有一个侦听器,并且每次调用_tabController.animateTo时,都会执行方法_handleTabChange,然后对其进行动画处理第一个标签.

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.

删除或评论此行

 _tabController.addListener(_handleTabChange);

它应该可以工作

这篇关于TabController不会改变Flutter TabBarView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 08:49