useTabController index never changes

Issue

I am using hooks for handling tab controller, the problem is when i print the current index of the controller it is right. But when i try to display it inside a text widget it is never changes! how could i use it?

The code is:

class TabBarDemo extends HookWidget {
  final List<Widget> list = const [
    Tab(icon: Icon(Icons.card_travel)),
    Tab(icon: Icon(Icons.add_shopping_cart)),
    Tab(icon: Icon(Icons.ac_unit)),
  ];

  @override
  Widget build(BuildContext context) {
    final _controller =
        useTabController(initialLength: list.length, initialIndex: 0);
    _controller.addListener(() {
      print("\n ${_controller.index} \n");
    });
    return Scaffold(
      appBar: AppBar(
        bottom: TabBar(
          onTap: (index) {},
          controller: _controller,
          tabs: list,
        ),
      ),
      body: TabBarView(
        controller: _controller,
        children: [
          Center(
              child: Text(
            '${_controller.index}',
          )),
          Center(
              child: Text(
            '${_controller.index}',
          )),
          Center(
              child: Text(
            '${_controller.index}',
          )),
        ],
      ),
    );
  }
}

Solution

You have to rebuild the tree using :
setState(() {
});

Answered By – Idriss

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.