Flutter界面开发:如何使图标与顶部文本对齐?
Flutter店铺头部图标与文本对齐问题
当前你的shopHeader组件中左侧图标位置偏低,无法和“Awesome Shop”文本垂直对齐,这是因为Row组件默认的crossAxisAlignment是CrossAxisAlignment.center,导致图标容器和Column的垂直中心对齐,而Column里的店铺名称文本是从顶部开始排列的,所以视觉上图标就显得偏低了。这里有两种简单的解决方法:
方案一:让组件垂直顶部对齐
给Row添加crossAxisAlignment: CrossAxisAlignment.start,让Row内的所有子组件都沿着垂直方向的顶部对齐,这样图标就能和店铺名称文本的顶部对齐了:
Widget shopHeader(var shopName, var shopAddress){ return Container( height: 200, margin: const EdgeInsets.all(10.0), child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, // 新增这一行 children: <Widget>[ Container( padding: const EdgeInsets.all(1.0), child: const Icon(Icons.home, color: Colors.black), decoration: const BoxDecoration( color: Colors.grey, // border color shape: BoxShape.circle, ), ), const SizedBox( width: 10, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( shopName, style: TextStyle(fontSize: 17), ), Text( shopAddress, style: TextStyle(fontSize: 14, color:Colors.black38), ), Padding( padding: EdgeInsets.only(left:0.0, right:0.0, top:20.0, bottom:0.0), child: SizedBox( width: 150, child: ElevatedButton( child: Text('Chat'), onPressed: () {}, )) ) ], ), ], ), ); }
方案二:让图标与文本基线对齐(视觉更和谐)
如果想要图标和文本的基线对齐(类似文字底部对齐的效果,视觉上更自然),可以把Row的crossAxisAlignment设置为CrossAxisAlignment.baseline,同时必须指定textBaseline参数:
Widget shopHeader(var shopName, var shopAddress){ return Container( height: 200, margin: const EdgeInsets.all(10.0), child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.baseline, // 修改为baseline对齐 textBaseline: TextBaseline.alphabetic, // 必须指定基线类型 children: <Widget>[ Container( padding: const EdgeInsets.all(1.0), child: const Icon(Icons.home, color: Colors.black), decoration: const BoxDecoration( color: Colors.grey, // border color shape: BoxShape.circle, ), ), const SizedBox( width: 10, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( shopName, style: TextStyle(fontSize: 17), ), Text( shopAddress, style: TextStyle(fontSize: 14, color:Colors.black38), ), Padding( padding: EdgeInsets.only(left:0.0, right:0.0, top:20.0, bottom:0.0), child: SizedBox( width: 150, child: ElevatedButton( child: Text('Chat'), onPressed: () {}, )) ) ], ), ], ), ); }
你可以根据自己的UI设计需求选择其中一种方案,测试后就能看到图标和文本完美对齐了。
内容的提问来源于stack exchange,提问作者anta40
相关产品推荐
相关产品推荐

