Search code examples
flutterdartflutter-layout

DefaultTabController without Scaffold?


I'm trying to use DefaultTabController in the middle of some widgets. So my TabBar could not be in AppBar and has to be down some widgets. So my problem is when I use TabBarView it crashes...

So here's an example of Flutter sample but no found how to do it without Scaffold.

final List<Tab> myTabs = <Tab>[
  Tab(text: 'LEFT'),
  Tab(text: 'RIGHT')];

Code

DefaultTabController(
  length: myTabs.length,
  child: Scaffold(
    appBar: TabBar(
      tabs: myTabs,
    ),
    body: TabBarView(
      children: myTabs.map((Tab tab) {
        final String label = tab.text.toLowerCase();
        return Center(
          child: Text(
            'This is the $label tab',
            style: const TextStyle(fontSize: 36),
          ),
        );
      }).toList(),
    ),
  ),
);

Here is another example of a TabBar I should do image

Real Code

class ProfileTabBarNavigation extends StatelessWidget {
 final List<Tab> myTabs = <Tab>[
   const Tab(text: kArtwork),
   const Tab(text: kPastJobs)];
@override
Widget build(BuildContext context) {
return DefaultTabController(
  length: 2,
  initialIndex: 0,
  child: Padding(
    padding: kPaddingTabBar,
    child: Container(
      padding: EdgeInsets.all(5.0),
      decoration: BoxDecoration(
        color: kLightGrey,
        borderRadius: BorderRadius.all(
          Radius.circular(50),
        ),
      ),
      child: Column(children: <Widget>[
        TabBar(
          tabs: myTabs,
          unselectedLabelColor: Colors.black54,
          labelColor: Colors.black,
          unselectedLabelStyle: kBoldText,
          labelStyle: kBoldText,
          indicatorSize: TabBarIndicatorSize.tab,
          indicator: BoxDecoration(
            shape: BoxShape.rectangle,
            borderRadius: BorderRadius.circular(50),
            color: Colors.white,
          ),
        ),
        TabBarView(
          children: myTabs.map((Tab tab) {
            final String label = tab.text.toLowerCase();
            return Center(
              child: Text(
                'This is the $label tab',
                style: const TextStyle(fontSize: 36),
              ),
            );
          }).toList(),
        ),
      ]),
    ),
  ),
);
}
}

Solution

  • Wrap your TabBarView with Expanded.

    Expanded(
     child: TabBarView(//...),
    ),
    

    Try it on DartPad