【问题标题】:flutter TabBarView doesn't change by TabController颤动的 TabBarView 不会被 TabController 改变
【发布时间】:2019-09-19 17:02:34
【问题描述】:

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

这是我的示例,每当我滑动到 RIGHT 时,它都应该向左动画化,因为选项卡更改侦听器会自动调用 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),
      ),
    );
  }
}

【问题讨论】:

  • 评论“_tabController.animateTo(0);”在 _handleTabChange() 中它会起作用

标签: flutter


【解决方案1】:

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

删除或评论此行

 _tabController.addListener(_handleTabChange);

它应该可以工作

【讨论】:

  • 感谢您的回复。但这只是一个测试示例,我想做的是以编程方式更改选项卡。所以我希望在我滑动到 RIGHT 后立即将选项卡更改为 LEFT,但我不明白为什么 TabBarView 部分没有改变。
  • 您可以使用 _tabController .animateTo 以编程方式更改选项卡,就像您在按下 FloatingActionButton 时所做的那样,但您必须删除或评论我在回答中告诉您的行:)
猜你喜欢
  • 2020-04-27
  • 2021-01-07
  • 2019-03-24
  • 2023-02-06
  • 2021-01-01
  • 2022-08-24
  • 1970-01-01
  • 2021-04-13
  • 2019-10-03
相关资源
最近更新 更多