How to align `TabBar` to the left with a custom st

2020-04-21 04:37发布

问题:

I'm currently working on a Flutter app in which I'd like to display the TabBar starting on the left. If an AppBar has a leading property I'd like to indent the starting position of the TabBar to match it. Then on scroll, it would still pass through and not leave white area.

This is the code that I have that currently displays a TabBar in the middle of the AppBar:

AppBar(
  bottom: TabBar(
    isScrollable: true,
    tabs: state.sortedStreets.keys.map(
      (String key) => Tab(
        text: key.toUpperCase(),
      ),
    ).toList(),
  ),
);

回答1:

Maybe your TabBar isn't filled up the whole horizontal area. What happen if you wrap the TabBar within another Container that expanded the whole width like this.

Container(
  width: double.infinity
  child: TabBar(
    ...
    ...
  )
)



回答2:

The Flutter TabBar widget spaces out the tabs evenly when the scrollable property of TabBar is set to false, as per the comment in the tabs.dart source code:

// Add the tap handler to each tab. If the tab bar is not scrollable
// then give all of the tabs equal flexibility so that they each occupy
// the same share of the tab bar's overall width.

So you can get a left-aligned TabBar by using:

isScrollable: true,

and if you want to use indicators that are the same width as the Tab labels (eg. as you would by if you set indicatorSize: TabBarIndicatorSize.label) then you may also want to have a custom indicator set like so:

TabBar(
  indicator: UnderlineTabIndicator(
  borderSide: BorderSide(
    width: 4,
    color: Color(0xFF646464),
  ),
  insets: EdgeInsets.only(
    left: 0,
    right: 8,
    bottom: 4)),
  isScrollable: true,
  labelPadding: EdgeInsets.only(left: 0, right: 0),
  tabs: _tabs
    .map((label) => Padding(
      padding:
        const EdgeInsets.only(right: 8),
      child: Tab(text: "$label"),
   ))
   .toList(),
)

Example of what this will look like:



回答3:

You can use Align Widget to align the tabs of the TabBar to left, which will be the child of PreferredSize.

This worked for me:

  bottom: PreferredSize(
    preferredSize: Size.fromHeight(40),
    ///Note: Here I assigned 40 according to me. You can adjust this size acoording to your purpose.
    child: Align(
      alignment: Alignment.centerLeft,
      child: TabBar(
        isScrollable: true,
        tabs: state.sortedStreets.keys.map(
          (String key) => Tab(
              text: key.toUpperCase(),
          ),
        ).toList(),
      ),
    ),
  ),

In case you only need TabBar in body you can remove the PreferredSize Widget.