Flutter中如何让NavigationRail的Destination文本居中?
解决思路
NavigationRail的label区域默认带有布局约束,仅用Center包裹文本无法让文本在导航项的整个可用宽度内居中。通过让文本容器占满导航项宽度,并给文本设置居中对齐属性,就能实现目标效果。
修改后的完整代码
@override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppBar( backgroundColor: AppColors.blue, title: Text(subCategory.categoryTitle!), ), body: Row(children: [ LayoutBuilder(builder: (context, constraint) { return SingleChildScrollView( child: ConstrainedBox( constraints: BoxConstraints(minHeight: constraint.maxHeight), child: IntrinsicHeight( child: SizedBox( width: 80, child: NavigationRail( labelType: NavigationRailLabelType.all, destinations: <NavigationRailDestination>[ for (var i = 0; i < subCategory.subCategory!.length; i++) NavigationRailDestination( icon: Icon(Icons.shop), // selectedIcon: Icon(Icons.favorite), label: SizedBox( width: double.infinity, child: Text( subCategory.subCategory![i].subCategoryName!, textAlign: TextAlign.center, style: TextStyle(color: Colors.black), ), ), ), ], selectedIndex: selected, onDestinationSelected: (value) { setState(() { selected = value; }); }, ), )), ), ); }), ]), ), ); }
关键调整说明
SizedBox(width: double.infinity):让文本容器占满导航项的整个宽度,消除默认约束带来的限制textAlign: TextAlign.center:确保文本在容器内水平居中,无论文本长短都能保持居中状态
内容的提问来源于stack exchange,提问作者thinkcode
相关产品推荐
相关产品推荐

