Flutter tabcontroller索引不响应tabbarview中的更改

时间:2018-12-18 05:01:48

标签: flutter

Flutter tabcontroller检测到选项卡中的更改,但不知道选项卡视图中的更改。

侦听器导致floatingactionbutton的文本更改,但是当标签栏视图更改时没有响应。

class TabPageState extends State<TabPage> with SingleTickerProviderStateMixin {

  TabController _controller;
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _controller = TabController(vsync: this, length: 2);
    _controller.addListener(_handleTabSelection);
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Tab'),
        bottom: TabBar(
          controller: _controller,
          tabs: <Widget>[
            Tab(icon: Icon(Icons.laptop_mac),),
            Tab(icon: Icon(Icons.desktop_mac),),
          ],
        ),
      ),
      body: TabBarView(
        controller: _controller,
        children: <Widget>[
          Center(child: Text('laptop'),),
          Center(child: Text('desctop'),),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){},
        child: Text('$_currentIndex'),
      ),
    );
  }

  _handleTabSelection() {
    if (_controller.indexIsChanging) {
      setState(() {
        _currentIndex = _controller.index;
      });
    }
  }
}

2 个答案:

答案 0 :(得分:2)

只需删除条件:

  if (_controller.indexIsChanging) {

由于每次您开始从previousIndex更改为currentIndex时,都需要重新构建窗口小部件,并且_controller.index与初始索引相同。

这应该有效:

            _handleTabSelection() {
                  setState(() {
                    _currentIndex = _controller.index;
                  });
              }

答案 1 :(得分:2)

医生说:

indexIsChanging :当我们将[previousIndex]动画化为[index]时为true,
调用[animateTo]的后果。这个值是真的 ////用户触发的[animateTo]动画期间 点击[TabBar]选项卡。当[offset]更改为///时为false 用户拖动(和“拖动”)[TabBarView]的后果。

  bool get indexIsChanging => _indexIsChangingCount != 0;
  int _indexIsChangingCount = 0;

代码:

  TabController _controller;
  int _selectedIndex = 0;

  List<Widget> list = [
    Tab(icon: Icon(Icons.card_travel)),
    Tab(icon: Icon(Icons.add_shopping_cart)),
  ];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // Create TabController for getting the index of current tab
    _controller = TabController(length: list.length, vsync: this);

    _controller.addListener(() {
      setState(() {
        _selectedIndex = _controller.index;
      });
      print("Selected Index: " + _controller.index.toString());
    });
  }

示例: https://github.com/jitsm555/Flutter-Problems/tree/master/tab_bar_tricks

输出:

enter image description here