Flutter中隐藏已填充TextField的Label及文本居中问题求助
解决TextField的两个显示问题
问题1:输入内容后隐藏Label
把原代码里的label替换成hint(InputDecoration的hint属性支持自定义Widget样式),用户输入内容后,hint会自动隐藏,刚好匹配需求。
问题2:未输入时Label居中、输入文本居中
- 在
TextField组件上添加textAlign: TextAlign.center,保证用户输入的文本居中显示; - 给作为hint的
Text组件设置textAlign: TextAlign.center,确保未输入时提示文本在组件空间内居中。
修改后的完整代码:
TextField( controller: height_controller, keyboardType: const TextInputType.numberWithOptions(), textAlign: TextAlign.center, // 控制输入文本居中 decoration: InputDecoration( hint: const Text( 'Height', style: TextStyle( color: Colors.white70, fontSize: 30, fontWeight: FontWeight.w300, ), textAlign: TextAlign.center, // 控制提示文本居中 ), ), ),
补充方案(若需保留固定Label逻辑)
如果需要Label始终固定在输入框内、输入后被内容覆盖,可改用labelText并配合以下设置:
TextField( controller: height_controller, keyboardType: const TextInputType.numberWithOptions(), textAlign: TextAlign.center, decoration: const InputDecoration( labelText: 'Height', floatingLabelBehavior: FloatingLabelBehavior.never, // 禁止Label浮动 labelStyle: TextStyle( color: Colors.white70, fontSize: 30, fontWeight: FontWeight.w300, ), alignLabelWithHint: true, // 确保Label与输入内容对齐方式一致 ), ),
内容的提问来源于stack exchange,提问作者Hana.HD
相关产品推荐
相关产品推荐

