Flutter tab bar view dynamic height

HTML Content for Flutter Tab Bar View with Dynamic Height

When using Flutter’s TabBarView widget, the height can be dynamic based on the content inside. Here’s an example of how you can achieve this:

  
import 'package:flutter/material.dart';

class DynamicHeightTabBarView extends StatefulWidget {
  @override
  _DynamicHeightTabBarViewState createState() => _DynamicHeightTabBarViewState();
}

class _DynamicHeightTabBarViewState extends State with SingleTickerProviderStateMixin {
  TabController _tabController;
  
  List _tabs = [
    'Tab 1',
    'Tab 2',
    'Tab 3',
  ];
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this);
  }
  
  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dynamic Height TabBarView'),
        bottom: TabBar(
          controller: _tabController,
          tabs: _tabs.map((String tab) => Tab(text: tab)).toList(),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: _tabs.map((String tab) {
          return Container(
            color: Colors.blueGrey,
            child: Center(
              child: Text(
                tab,
                style: TextStyle(fontSize: 24, color: Colors.white),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: DynamicHeightTabBarView(),
  ));
}
  
  

In the above code, we create a StatefulWidget called DynamicHeightTabBarView. Inside its build method, we create a Scaffold with an AppBar that contains a TabBar widget. The TabBar is linked to a TabController, which defines the number of tabs and handles switching between them.

The body of the Scaffold contains a TabBarView, which also uses the same TabController to synchronize with the TabBar. Inside the TabBarView, we create a list of containers wrapped with the content of each tab. In this example, we use a simple container with a colored background and centered text displaying the tab name.

To achieve dynamic height, the height of the TabBarView will automatically adjust based on the content of the current tab. You can customize the content of each tab as per your requirement. Run the code on a Flutter project to see the dynamic height functionality in action.

Leave a comment