Add mandatory(*) for labelText in Input Decoration in Flutter
Asked Answered
D

3

5

I want to add asteric sign in InputDecoration labelText and change color(like red) of it so that user understand easily this field is required.

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

Expected result like this image Sample Image

Douai answered 2/8, 2019 at 5:57 Comment(4)
have any alternative to do this?Douai
is it possible? anyone help me to do this?Douai
I answered this with a solution than can be used with RichTextTrochilus
I have found answer in another thread - look at thisHooke
W
8

You can use label arguments inside InputDecoration parameters. This work both widgets TextField or 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,
       );
Wageworker answered 12/5, 2022 at 2:16 Comment(0)
T
3

You can use the Rich Text Widget like this

RichText getRequiredLabel(String fieldName) {
  return RichText(
      text: TextSpan(
          style: TextStyle(color: Colors.black),
          text: fieldName,
          children: [
        TextSpan(text: '*', style: TextStyle(color: Colors.red))
      ]));
}
Trochilus answered 3/10, 2021 at 3:0 Comment(0)
A
0

Is you want to preserve the original behavior styling, then use the example from the Flutter documentation:

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

Here is a link https://api.flutter.dev/flutter/material/InputDecoration/label.html

Agbogla answered 17/2 at 19:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.