有没有办法在DefaultTabController中添加监听器?

时间:2017-10-21 10:28:12

标签: dart flutter

在使用DefaultTabController时,我一直在尝试添加侦听器。但是,每次我添加TabController以获取TabBarTabBarView中的当前索引时,我都会失去它们之间的同步。

这是我的代码:

  @override
  Widget build(BuildContext context) {
    return new DefaultTabController(
      length: subPages.length,
      child: new Scaffold(
        appBar: appBar('homepage'),
        body: new Center(
          child: new NestedScrollView(
            headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
              return <Widget>[
                new SliverAppBar(
                  backgroundColor: Colors.white,
                  title: new TabBar(
                    labelColor: Colors.black,
                    indicatorColor: Colors.black,
                    labelStyle: new TextStyle(fontWeight: FontWeight.bold),
                    tabs: subPages.map((String str) => new Tab(text: str)).toList(),
                  ),
                ),
              ];
            },
            body: new TabBarView(
              children: subPages.map((String str) {
                return new ListView(
                  padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                  children: subPages.map((String str) {
                    return new Padding(
                      padding: const EdgeInsets.symmetric(vertical: 8.0),
                      child: new Text(str),
                    );
                  }).toList(),
                );
              }).toList(),
            ),
          ),
        ),
        floatingActionButton: new FloatingActionButton(
          backgroundColor: Colors.black,
          onPressed: null,
          tooltip: 'Increment',
          child: new Icon(Icons.add),
        ),
      ),
    );
  }

1 个答案:

答案 0 :(得分:0)

我用这个:

new DefaultTabController(
  child: Builder(
    builder: (context) {
   
      final tabController = DefaultTabController.of(context)!;
      tabController.addListener(() {
        print("New tab index: ${tabController.index}");
      });
    
      return Scaffold(
        ...
      );
    }
  ),
);