[Solved] No TabController for TabBar and TabBarView Flutter

In this post, we are going to show you how to solve 'No TabController for TabBarView and TabBar. When creating a TabBarView, you must either provide an explicit TabController using the "controller" property"' error in Flutter.

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞════════════════════════════
The following assertion was thrown building _BodyBuilder:
No TabController for TabBarView/TabBar.
When creating a TabBarView, you must either provide an explicit TabController using the "controller"
property, or you must ensure that there is a DefaultTabController above the TabBarView.
In this case, there was neither an explicit controller nor a default controller.

This error occurs if you have used TabBar() and TabBarView() without a Tab controller. To solve this issue, see the solution below:

To solve this error, you need to provide a tab controller before using TabBar() and TabBarView(). To provide the controller, just wrap your widget with DefaultTabController() widget before using tab widgets like below:

DefaultTabController( 
  initialIndex: 1,  //optional, starts from 0, select the tab by default
  length:3,
  child:Scaffold(
    //TabBar() and TabBarView() goes here
  )
)

DefaultTabController( 
  initialIndex: 1,  //optional, starts from 0, select the tab by default
  length:3,
  child:Scaffold(
      appBar: AppBar(
        title: Text("Tab in Flutter"),
        backgroundColor: Colors.lightGreen,
        bottom: TabBar(
                  tabs: [
                      Tab(text: "Home",),
                      Tab(text: "About Us",),
                      Tab(text: "Contact Us",)
                  ]
                ),
      ),
      
      body: TabBarView(
          children: [
              Container( //for first tab
                  height: 400,
                  color: Colors.red,
              ),
              Container( //for second tab
                  height: 400,
                  color: Colors.green,
              ),
              Container( //for third tab
                height: 400,
                  color: Colors.blue,
              )
          ]
      )
    )
)

In this way, you can solve "No TabController for TabBar and TabBarView" error in Flutter. 

No any Comments on this Article


Please Wait...