Home > Blockchain >  How to dynamically open a tab in Tabbar in Flutter?
How to dynamically open a tab in Tabbar in Flutter?

Time:11-23

So basically I have a widget which I Navigate to:

Navigator.of(context).pushNamed(Purchases.route, arguments: {"index": index});

The Purchases widget is simply an empty Widget with nothing except two tabs using TabBar, TabBarView, and TabController. The tabs are for pending and delivered. The idea is, when I navigate to the widget, the correct tab is the initial tab that is open.

For example: When I click pending on the previous widget, the navigator navigates to the Purchases widget and the pending tab is the initial tab that is open. When I click delivered on the previous widget, the navigator navigates to the Purchases widget and the delivered tab is the initial tab that is open.

I pass the index of the tab that I want opened and use it in the initState method and it works, however only partially.

void initState() {
    super.initState();
    _controller = TabController(length: 2, vsync: this);
    Future.delayed(Duration.zero, () {
      final args = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
      int index = args["index"];
      _controller.animateTo(index);
    });
}

This implementation works, however the tab isn't really initially open, its only animated after the tab at index 0 is opened. This is bad performance since I plan on making API calls whenever the tabs open and if the user didn't open/care for the tab at index 0, then its a useless API call.

I have tried:

void initState() {
    super.initState();
    final args = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
    int index = args["index"];
    _controller = TabController(length: 2, vsync: this, initialIndex: index);
}

This doesn't work because context isn't available for use and results in an error.

How could I properly get this to work? Thank You!

CodePudding user response:

So I did a little digging and found this to be the solution:

void didChangeDependencies() {
    super.didChangeDependencies();
    final args = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
    int index = args["index"];
    _controller = TabController(length: 2, vsync: this, initialIndex: index);
}

I guess initState wasn't the correct approach. didChangeDependencies does get called after every build whereas initState doesn't. Something to consider.

CodePudding user response:

Setting an initialIndex to the TabController is the right approach.

In order to have access to the context, you need call your API inside a separate function and then call it inside initState.

void apiCall(){
  //Call here your API (context accessible).
}
@override
initState((){
  ...
  apiCall();
  ...
});
  • Related