-1

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}',
          )),
        ],
      ),
    );
  }
}
  • 1
    it is because you need to rebuild your `Text` widget every time `index` changes - in most cases it is done by calling `State.setState` method (i see you are using 3rd party `HookWidget` so it can have its own rebuild methods) – pskink Oct 19 '21 at 08:48
  • make it as an answer to accept it, please. – Mariam Albarghouti Oct 19 '21 at 08:51
  • 2
    ok i looked at `HookWidget` and instead of `_controller.addListener` you need: `final _controller = useTabController(initialLength: ...); useListenable(_controller);` - now you are adding a listener multiple times – pskink Oct 19 '21 at 11:08

1 Answers1

0

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

Idriss
  • 354
  • 3
  • 10