Home > Software design >  useTabController index never changes
useTabController index never changes

Time:10-20

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}',
          )),
        ],
      ),
    );
  }
}

CodePudding user response:

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

  • Related