我目前正在开发一个 Flutter 应用程序,我想在其中显示从左侧开始的
TabBar
。如果 AppBar
具有前导属性,我想缩进 TabBar
的起始位置以匹配它。那么在卷轴上,它仍然会穿过,不会离开白色区域。
这是我目前在
TabBar
中间显示 AppBar
的代码:
AppBar(
bottom: TabBar(
isScrollable: true,
tabs: state.sortedStreets.keys.map(
(String key) => Tab(
text: key.toUpperCase(),
),
).toList(),
),
);
当 TabBar 的可滚动属性设置为 false 时,Flutter TabBar 小部件会均匀地分隔选项卡,如 tabs.dart 源代码中的注释:
// 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.
因此,您可以使用以下方法获得左对齐的 TabBar:
isScrollable: true,
如果您想使用与选项卡标签宽度相同的指示器(例如,如果您设置
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(),
)
示例:
您可以使用 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(),
),
),
),
如果您只需要正文中的TabBar,您可以删除PreferredSize小部件。
也许你的
TabBar
没有填满整个水平区域。如果将 TabBar
包裹在另一个像这样扩展整个宽度的容器中,会发生什么。
Container(
width: double.infinity
child: TabBar(
...
...
)
)
默认使用常量 kToolbarHeight
将选项卡栏与相同的标题栏高度对齐bottom: PreferredSize(
preferredSize: const Size.fromHeight(kToolbarHeight),
child: Align(
alignment: Alignment.centerLeft,
child: TabBar(/*your code*/),
),
),
在这里对齐标签栏完美解决方案:
bottom: PreferredSize(
preferredSize: Size.fromHeight(kToolbarHeight),
child: Align(
alignment: Alignment.centerLeft,
child: TabBar(
indicatorSize: TabBarIndicatorSize.tab,
indicatorColor: AppColors.cyan_blue,
labelColor: AppColors.cyan_blue,
indicator: UnderlineTabIndicator(
borderSide: BorderSide(
width: 4.0,
color: AppColors.cyan_blue,
),
insets: EdgeInsets.only(left: 10, right: 110.0)),
labelStyle: TextStyle(fontSize: 16.0),
//For Selected tab
unselectedLabelStyle: TextStyle(fontSize: 12.0),
isScrollable: true,
labelPadding: EdgeInsets.symmetric(horizontal: 10.0),
tabs: [
Container(
child: Tab(
text: "Profile Summary\t\t\t",
),
),
Container(
child: Tab(
text: "Business summary",
),
),
],
),
),
),
这会对您有帮助
kToolbarHeight
和Alignment.centerLeft
bottom: PreferredSize(
preferredSize: const Size.fromHeight(kToolbarHeight),
child: Align(
alignment: Alignment.centerLeft,
//alignment: AlignmentDirectional.centerStart
child: TabBar(
isScrollable: true,
indicatorColor: Colors.white,
tabs: _tabs,
controller: _tabController,
),
),
),
这只是修复它
isScrollable: true,
tabAlignment: TabAlignment.start