Flutter ListTile宽度设置问题:如何使左侧ListTile固定宽度
解决Flutter固定宽度区号输入框+自适应手机号输入框的问题
嘿,我明白你的需求啦——要把原来均分空间的两个输入框改成左侧固定宽度的区号框+右侧占满剩余空间的手机号框,这就给你调整代码:
首先,你原来的代码里用了Flexible和Expanded导致两个输入框均分空间,咱们把第一个输入框改成固定宽度,同时注意别让两个输入框共用同一个controller(不然输入内容会串哦)。修改后的代码如下:
Row( children: <Widget>[ // 固定宽度的区号输入框 SizedBox( width: 100, // 这里设置你想要的固定宽度,可按需调整 child: ListTile( contentPadding: EdgeInsets.symmetric(horizontal: 8), // 调整内边距让输入框更紧凑 title: TextFormField( controller: _areaCodeController, // 换成单独的区号controller,避免和手机号串数据 keyboardType: TextInputType.phone, decoration: InputDecoration( hintText: translate('contact_list.area_code'), // 改成对应区号的提示文字 ), validator: (value) { return Helpers.checkInput(value); }, ), ), ), // 自适应剩余空间的手机号输入框 Expanded( child: ListTile( contentPadding: EdgeInsets.symmetric(horizontal: 8), title: TextFormField( controller: _phoneNumberController, // 手机号专属controller keyboardType: TextInputType.phone, decoration: InputDecoration( hintText: translate('contact_list.number'), ), validator: (value) { return Helpers.checkInput(value); }, ), ), ), ], )
关键改动说明:
- 把第一个
Flexible换成SizedBox并设置固定width,直接控制区号输入框的宽度,你可以根据UI需求调整这个数值(比如80、100都可以)。 - 给区号输入框单独创建了
_areaCodeController,避免和手机号输入框共用controller导致输入内容互相覆盖。 - 调整了
ListTile的contentPadding,让输入框更紧凑,符合区号输入框“较小”的需求(如果不需要图标,也可以直接去掉leading)。 - 右侧保持
Expanded,确保手机号输入框自动占满Row的剩余空间。
如果觉得用ListTile有点冗余,也可以直接用Container包裹TextFormField,代码会更简洁:
Row( children: <Widget>[ SizedBox( width: 100, child: Padding( padding: EdgeInsets.symmetric(horizontal: 8), child: TextFormField( controller: _areaCodeController, keyboardType: TextInputType.phone, decoration: InputDecoration( hintText: translate('contact_list.area_code'), ), validator: (value) => Helpers.checkInput(value), ), ), ), Expanded( child: Padding( padding: EdgeInsets.symmetric(horizontal: 8), child: TextFormField( controller: _phoneNumberController, keyboardType: TextInputType.phone, decoration: InputDecoration( hintText: translate('contact_list.number'), ), validator: (value) => Helpers.checkInput(value), ), ), ), ], )
这样就完全符合你的需求啦,左侧固定宽度显示区号,右侧自适应显示手机号~
内容的提问来源于stack exchange,提问作者Dani
相关产品推荐
相关产品推荐

