Flutter开发时Row内第二个Text设置右侧padding不生效如何解决
问题原因
- 外层父
Row默认按子组件的实际尺寸分配空间,你将两个Text分别放在独立的Row中,这两个Row只会适配自身内容的宽度,你给第二个Text加的EdgeInsets.only(right: 50)是在Text组件的右侧添加内边距,但此时外层Row没有多余的横向空间,所以这个padding不会推动Text靠左对齐,看起来就像未生效。 - 布局层级逻辑错误,两个文本是上下排列的关系,应该放在同一个
Column组件中,而不是各自包裹一个Row。
解决方案
调整布局结构,用Expanded包裹存放文本的Column,占满头像之外的剩余横向空间,再调整文本的padding即可实现预期的对齐效果,修正后代码参考:
Row( children: [ Padding( padding: const EdgeInsets.only(left: 15), child: CircleAvatar( radius: 30.0, backgroundImage: NetworkImage('你的头像地址'), backgroundColor: Colors.transparent, ), ), Expanded( child: Padding( // 统一设置文本区域的左右边距 padding: const EdgeInsets.only(left: 10, right: 50), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text( "Ammar Mohib", style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500), ), SizedBox(height: 8), Text( "message", style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500), ), ], ), ), ), ], )
如果后续需要在右侧添加时间、已读标识之类的组件,直接放在Expanded的后面即可。
内容的提问来源于stack exchange,提问作者Ammar Mohib
相关产品推荐
相关产品推荐

