Gha*_*ebl 9 flutter flutter-layout

我有一个自定义文本字段,但如图所示,底部文本字段看起来如此模糊和空白,即使该字段未聚焦,我也希望保持提示显示,我如何在颤动中实现这一点?
这是我的小部件代码:
Container(
margin: EdgeInsets.all(20),
child: TextFormField(
autofocus: true,
textAlign: TextAlign.right,
decoration: InputDecoration(
enabledBorder: const OutlineInputBorder(
borderSide: const BorderSide(color: Color(0xff0E9447), width: 2.0),
),
focusedBorder: const OutlineInputBorder(
borderSide: const BorderSide(color: Color(0xff0E9447), width: 2.0),
),
hintText: AppStrings.email,
labelText: AppStrings.email,
alignLabelWithHint: true,
hintStyle: TextStyle(color: AppColors.primaryColorLight),
),
),
),
Run Code Online (Sandbox Code Playgroud)
Phi*_*ins 27
如果您希望标签在 TextField 顶部可见,并且同时显示提示,您只需添加:
floatingLabelBehavior: FloatingLabelBehavior.always
Run Code Online (Sandbox Code Playgroud)
到TextFields InputDecoration(装饰)。
(在撰写本文时,有一个错误只会在焦点上显示提示和后缀,这已在最近的 PR 中修复,很快就会提供,请参阅GitHub 问题)
完整示例
TextFormField(
controller: textController,
style: theme.textTheme.bodyText2,
keyboardType: keyboardType ?? TextInputType.number,
enableInteractiveSelection: false,
decoration: InputDecoration(
labelText: labelText,
labelStyle: theme.textTheme.headline6,
suffixText: suffixText ?? '',
border: OutlineInputBorder(
borderSide:
BorderSide(color: theme.textTheme.bodyText2.color, width: 2),
),
hintText: '0.0',
floatingLabelBehavior: FloatingLabelBehavior.always),
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
onChanged: (String text) => onChange(text),
);
Run Code Online (Sandbox Code Playgroud)
理想情况下,在 Flutter 中,您不能同时执行此操作hintText并labelText以两种不同的方式表现。只要用户不关注它labelText就会显示。hintText一旦用户单击文本字段,labelText动画就会移动到特定位置,而 ahintText会保持可见,直到用户键入内容。
因此,一起使用labelText和hintText没有任何意义,因为 TextField 会hintText在为标签设置动画时擦除 。
然而,通过一些额外的努力,您可以使用Stack小部件来解决您的问题。
声明一个类变量(相关类内、任何代码块之外的变量)来存储TextEditingController.
TextEditingController _controller;
Run Code Online (Sandbox Code Playgroud)
并在你的类的 initState() 中初始化,
_controller= TextEditingController();
Run Code Online (Sandbox Code Playgroud)
解决方案代码:
Container(
margin: EdgeInsets.all(20),
child: Stack(
children : <Widget>[
TextFormField(
autofocus: true,
textAlign: TextAlign.right,
decoration: InputDecoration(
enabledBorder: const OutlineInputBorder(
borderSide: const BorderSide(color: Color(0xff0E9447), width: 2.0),
),
focusedBorder: const OutlineInputBorder(
borderSide: const BorderSide(color: Color(0xff0E9447), width: 2.0),
),
labelText: AppStrings.email,
alignLabelWithHint: true,
hintStyle: TextStyle(color: AppColors.primaryColorLight),
),
),
(_controller.text=="")
?
Text(
AppStrings.email,
style: TextStyle(
color: Colors.grey
// Style it according to your requirement / To make it look like hintText
),
)
:
Container();
],
),
),
Run Code Online (Sandbox Code Playgroud)
上述代码的基本逻辑:如果 TextField 没有任何文本,则显示(提示)Text
小部件,否则不显示任何内容。
有一种方法可以解决这个问题。使用该labelText属性并设置floatingLabelBehavior: FloatingLabelBehavior.never.
这样,您将始终看到提示,并且当用户单击文本字段时,提示就会消失。
| 归档时间: |
|
| 查看次数: |
10426 次 |
| 最近记录: |