Search code examples
fluttertabspadding

Flutter TabBar unwanted space on first label


`The space before the first label 'Mon' is there even when padding margins are zero. Tried setting paddings to zero but there is still some spaces on the left on the first label.

enter image description here

    import 'package:flutter/material.dart';

    void main() {
      runApp(MyApp());
    }

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: MyHomePage(),
        );
      }
    }

    class MyHomePage extends StatelessWidget {
      final List<String> daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

      @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Days of the Week'),
      ),
      body: Padding(
        padding: EdgeInsets.zero, 
        child: DefaultTabController(
          length: daysOfWeek.length,
          initialIndex: 0,
          child: Column(
            children: <Widget>[
              Container(
                constraints: const BoxConstraints.expand(height: 50),
                color: Colors.grey[300],
                child: TabBar(
                  isScrollable: true,
                  indicatorColor: Colors.deepPurple,
                  tabs: daysOfWeek.map((String day) {
                    return Tab(
                      child: Text(
                        day,
                        style: const TextStyle(
                          fontWeight: FontWeight.bold,
                          letterSpacing: 0.5,
                          color: Colors.black,
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ),
              Expanded(
                child: TabBarView(
                  children: daysOfWeek.map((String day) {
                    return DayPage(day: day);
                  }).toList(),
                ),
              ),
            ],
          ),
        ),
          ),
        );
      }
    }

    class DayPage extends StatelessWidget {
      final String day;

      const DayPage({required this.day});

      @override
      Widget build(BuildContext context) {
        return Center(
          child: Text(
            'Content for $day',
            style: TextStyle(fontSize: 20),
          ),
        );
      }
    }

Solution

  • This is one of the breaking changes from the Flutter 3.16 update. To fix it, follow the migration guide to specify your desired alignment in tabAlignment:

    TabBar(
      tabAlignment: TabAlignment.start,
      // ...
    )