Home > Back-end >  DefaultTabController.of always return null
DefaultTabController.of always return null

Time:01-23

I have a flutter app with a DefaultTabController, at multiple places in the code I tried to get the associated TabController, but I go null.

TabController? c = DefaultTabController.of(context);

I have tried just after the widget creation and also at other places, but I always receive null.

If someone has an idea why and how to solve this ?

CodePudding user response:

You need to make sure you are trying to access the DefaultTabController in a context that actually has a DefaultTabController. In many cases, this means adding an extra Builder widget:

Scaffold(
body: SafeArea(
  child: DefaultTabController(
    initialIndex: 0,
    length: 3,
    child: Builder( // Add this
      builder: (context) {
        return Column(
          children: [
            TabBar(
              controller: DefaultTabController.of(context),
              labelColor: Colors.black,
              tabs: [
                Tab(text: 'One'),
                Tab(text: 'Two'),
                Tab(text: 'Three'),
              ],
            ),
            Expanded(child: Center(
              child: OutlinedButton(
                child: Text('Three'),
                onPressed: (){
                  DefaultTabController.of(context)?.animateTo(2);
                },
              ),
            ))
          ],
        );
      }
    ),
  ),
),
);
  • Related