Flutter中的Input Decoration中为labelText添加必填(*)

问题描述 投票:0回答:4

我想在

InputDecoration
labelText 中添加星号并更改其颜色(如红色),以便用户轻松理解此字段是必需的。

TextField(
    autofocus: true,
    controller: _nameCtrlr,
    keyboardType: TextInputType.text,
    decoration: InputDecoration(
    labelText: "Name *",
   ))

预期结果如下图所示 Sample Image

flutter dart flutter-layout label
4个回答
6
投票

您可以在

label
参数内使用
InputDecoration
参数。这适用于小部件
TextField
TextFormField

TextField(
        decoration: InputDecoration(
          label: Row(
            children: [
              const Text('*', style: TextStyle(color: Colors.red)),
              Padding(
                padding: EdgeInsets.all(3.0),
              ),
              Text("Name")
            ],
          ),
        ),
        controller: _nameCtrlr,
        autofocus: true,
        keyboardType: TextInputType.text,
       );

3
投票

您可以像这样使用富文本小部件

RichText getRequiredLabel(String fieldName) {
  return RichText(
      text: TextSpan(
          style: TextStyle(color: Colors.black),
          text: fieldName,
          children: [
        TextSpan(text: '*', style: TextStyle(color: Colors.red))
      ]));
}

0
投票

是的,伙计,你可以做到。

TextField(
    autofocus: true,
    controller: _nameCtrlr,
    keyboardType: TextInputType.text,
    decoration: InputDecoration(
    labelText: "Name \*",
   ))

“\”符号将帮助编译器区分星号(*)和乘法。


0
投票

如果您想保留原始的行为样式,请使用 Flutter 文档中的示例:

TextField(
    decoration: InputDecoration(
      label: Text.rich(
        TextSpan(
          children: <InlineSpan>[
            WidgetSpan(
              child: Text(
                'Username',
              ),
            ),
            WidgetSpan(
              child: Text(
                '*',
                style: TextStyle(color: Colors.red),
              ),
            ),
          ],
        ),
      ),
    ),
  )

这是一个链接https://api.flutter.dev/flutter/material/InputDecoration/label.html

© www.soinside.com 2019 - 2024. All rights reserved.