如何在Flutter中获取当前的Tab索引?

时间:2020-06-18 10:59:47

标签: flutter

我正在使用长度为2的TabController。我想对同一选项卡使用相同的Screen,并希望基于当前活动的选项卡显示不同的操作。但是,当我在两个选项卡屏幕上打印索引时,我得到的索引都是相同的。为什么? 这是我的标签页控制器:

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        bottom: PreferredSize(
          preferredSize: Size.fromHeight(32),
          child: Container(
            decoration: BoxDecoration(
              color: Color(0xFF111328),
              borderRadius: BorderRadius.circular(5),
            ),
            child: SafeArea(
              child: Column(
                children: <Widget>[
                  TabBar(
                    controller: _tabController,
                    indicator: UnderlineTabIndicator(
                      borderSide: BorderSide(color: Colors.white, width: 3),
                      insets: EdgeInsets.fromLTRB(56, 0, 56, 8),
                    ),
                    labelColor: kLabelColor,
                    labelStyle: kLabelStyle,
                    unselectedLabelColor: kUnselectedLabelColor,
                    indicatorWeight: kIndicatorWeight,
                    tabs: [
                      TabView(
                        text: "Home",
                        iconData: Icons.home,
                      ),
                      TabView(
                        text: 'Favourites',
                        iconData: Icons.favorite,
                      ), 
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
      body: TabBarView(
        children: <Widget>[
          MyTab(tabIndex: _tabController.length),
          MyTab(tabIndex: _tabController.index)
        ],
        controller: _tabController,
      ),
    );
}

这是上面的代码中用作TabBarView的MyTab视图屏幕

class MyTab extends StatefulWidget {
  MyTab({this.tabIndex});
  final int tabIndex;
  @override
  _MyTabState createState() => _MyTabState();
}

class _MyTabState extends State<MyTab> {
  _initImages() async {
    print(widget.tabIndex);                            // Always print 0
    AssetsImages assetsImages = AssetsImages(context: context);
    List imagePaths = await assetsImages.initImagesList();
    setState(() {
      imagesList = imagePaths;
    });
  }

  void initState() {
    super.initState();
    _initImages();
  }


}

2 个答案:

答案 0 :(得分:0)

您需要使用onTap()假发的 TabBar 方法

  • 点击TabBar时调用的可选回调。

示例代码

onTap: (tabIndex) {
   //selected tab tabIndex
},

完整示例代码

import 'package:flutter/material.dart';

void main() => runApp(HomeScreen());

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenPage createState() => _HomeScreenPage();
}

class _HomeScreenPage extends State<HomeScreen> with SingleTickerProviderStateMixin {
  TabController tabController;

  @override
  void initState() {
    super.initState();
    tabController = new TabController(length: 2, vsync: this);

    tabController.addListener(_getActiveTabIndex);
  }

  void _getActiveTabIndex() {
    _selectedIndex = tabController.index;
    debugPrint('CURRENT_PAGE $_selectedIndex');
  }

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

  int _selectedIndex = 0;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
        theme: ThemeData(
            primarySwatch: Colors.purple, brightness: Brightness.light, accentColor: Colors.red),
        darkTheme: ThemeData(
          brightness: Brightness.dark,
        ),
        home: Scaffold(
          appBar: AppBar(
            title: Text("Home"),
            centerTitle: true,
            bottom: TabBar(
              indicatorColor: Colors.blue,
              unselectedLabelColor: Colors.grey,
              labelColor: Colors.white,
              isScrollable: false,
              onTap: (tabIndex) {
                setState(() {
                  _selectedIndex = tabIndex;
                });
              },
              // to customise tab indicator
              indicator: UnderlineTabIndicator(
                  borderSide: BorderSide(width: 5.0, color: Colors.blue),
                  insets: EdgeInsets.symmetric(horizontal: 16.0)),
              tabs: <Widget>[
                Tab(
                  icon: Icon(Icons.favorite_border),
                  child: Text("One"),
                ),
                Tab(
                  icon: Icon(Icons.favorite),
                  child: Text("Two"),
                ),
              ],
              controller: tabController,
            ),
          ),
          body: TabBarView(
            children: <Widget>[
              Text("Page One"),
              Text("Page Two"),
            ],
            controller: tabController,
          ),
        ));
  }
}

class MyBody extends StatelessWidget {
  final String title;

  MyBody(this.title);

  final mySnackBar = SnackBar(
    content: Text(
      "Hello There!",
      style: TextStyle(color: Colors.white),
    ),
    duration: Duration(seconds: 3),
    backgroundColor: Colors.blue,
  );

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          RaisedButton(
              child: Text(title + "  Click me"),
              onPressed: () => {Scaffold.of(context).showSnackBar(mySnackBar)}),
        ],
      ),
    );
  }
}

答案 1 :(得分:0)

TabBar中缺少

onTap()

    TabBar(
          onTap: (index) { // It gives current selected index 0 for First Tab , second 1, like....
            print("Index of Tab:" + index.toString());
          },
         //.......
        ),