Flutter中点击TextFormField出现溢出错误,求组件包裹方案
解决Flutter TextFormField点击时的溢出问题
问题原因:当前页面使用固定高度的Container包裹Column,点击输入框弹出软键盘后,页面可用垂直空间被压缩,Column的总高度超过剩余显示空间,从而触发溢出错误。
修复方案
将Column包裹在SingleChildScrollView组件中,替换原来的Container结构。SingleChildScrollView会在内容高度超过可用空间时允许垂直滚动,避免溢出。
修改后的页面主体代码:
return Scaffold( body: SingleChildScrollView( child: Column( children: [ Padding( padding: const EdgeInsets.only(top: 50), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Padding( padding: EdgeInsets.only(top: 2), child: FaIcon( FontAwesomeIcons.compass, color: orange, size: 26, ), ), ], ), ), SizedBox(height: 25), Text( 'The final step for exploration.', style: homepageSubtitle, ), SizedBox(height: 50), TextFormWidget( onChanged: () => null, controller: _usernameController, labelText: 'Username', hintText: 'example@gmail.com'), TextFormWidget( onChanged: (value) => _checkPassword(value), controller: _passwordController, labelText: 'Password', hintText: 'Min. 8 characters'), // 添加底部padding避免输入框被键盘完全遮挡 SizedBox(height: 20), ], ), ), );
额外注意点
自定义TextFormWidget中的onChanged参数写法有误:
原代码:onChanged: onChanged()
正确写法:onChanged: onChanged
因为onChanged是回调函数,加括号会导致页面初始化时立即执行该函数,而非输入变化时触发。修正后的TextFormWidget代码:
return Column( children: [ Padding( padding: const EdgeInsets.symmetric( horizontal: 20, vertical: 20, ), child: TextFormField( onChanged: onChanged, // 修正此处 keyboardType: TextInputType.text, controller: controller, decoration: InputDecoration( contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), labelText: labelText, hintText: hintText, labelStyle: labelTextStyle, hintStyle: hintTextStyle, ), ), ), ], );
内容的提问来源于stack exchange,提问作者ckot
相关产品推荐
相关产品推荐

