如何将“TabBar”与自定义起始位置向左对齐

odo*_*ers 12 padding tabbar dart flutter

我目前正在开发一个 Flutter 应用程序,我想在其中显示TabBar左侧的开始。如果 anAppBar有一个领先的属性,我想缩进 的起始位置TabBar以匹配它。然后在滚动时,它仍然会通过而不离开白色区域。

这是我目前TabBar在中间显示 a 的代码AppBar

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

Mak*_*aks 14

根据tabs.dart 源代码中的注释,当 TabBar 的 scrollable 属性设置为 false 时,Flutter TabBar 小部件均匀地隔开选项卡:

// 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.
Run Code Online (Sandbox Code Playgroud)

因此,您可以使用以下方法获得左对齐的 TabBar:

isScrollable: true,
Run Code Online (Sandbox Code Playgroud)

并且如果您想使用与 Tab 标签宽度相同的指标(例如,如果您设置indicatorSize: TabBarIndicatorSize.label),那么您可能还需要像这样设置自定义指标:

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(),
)
Run Code Online (Sandbox Code Playgroud)

这将是什么样子的示例:

在此处输入图片说明


Inq*_*r K 10

也许你TabBar没有填满整个水平区域。如果将 包裹TabBar在另一个像这样扩展了整个宽度的 Container 中会发生什么。

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

Run Code Online (Sandbox Code Playgroud)


Ada*_*ava 8

您可以使用Align Widget 将TabBar的选项卡向左对齐,这将是 PreferredSize 的子项。

这对我有用:

  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(),
      ),
    ),
  ),
Run Code Online (Sandbox Code Playgroud)

如果您只需要正文中的TabBar,您可以删除PreferredSize小部件。


小智 7

这只是修复它

isScrollable: true,
tabAlignment: TabAlignment.start  
Run Code Online (Sandbox Code Playgroud)


小智 5

默认情况下,要将标签栏与相同的标题栏高度对齐,请使用常量kToolbarHeight

bottom: PreferredSize(
  preferredSize: const Size.fromHeight(kToolbarHeight),
  child: Align(
  alignment: Alignment.centerLeft,
  child: TabBar(/*your code*/),
 ),
),
Run Code Online (Sandbox Code Playgroud)