okaryo.log

Displaying Flutter TextField Labels at the Top and Changing Positions | okaryo.log

Displaying Flutter TextField Labels at the Top and Changing Positions

    #Flutter

What I want to do

I will introduce the implementation on the Flutter side for the following cases:

  • Display the label at the top of the TextField even when it’s not focused
  • Change the label position

You can create a UI like the one below.

Target Outcome

Display the label at the top

You can achieve this by specifying FloatingLabelBehavior.always for the floatingLabelBehavior property of the InputDecoration class.

const TextField(
  decoration: InputDecoration(
    floatingLabelBehavior: FloatingLabelBehavior.always,
    labelText: 'Label Name 1',
    hintText: 'Hint Text 1',
    hintStyle: TextStyle(color: Colors.grey),
    border: OutlineInputBorder(),
  ),
),

FloatingLabelBehavior is an enum, and other values include the default auto and never.

Change the label position

You can achieve this by specifying FloatingLabelAlignment.center for the floatingLabelAlignment property of the InputDecoration class.

const TextField(
  decoration: InputDecoration(
    floatingLabelAlignment: FloatingLabelAlignment.center,
    labelText: 'Label Name 2',
    hintText: 'Hint Text 2',
    hintStyle: TextStyle(color: Colors.grey),
    border: OutlineInputBorder(),
  ),
),

FloatingLabelAlignment is not an enum, but it has constants center and start, so you can use it like enum.


Related Posts
Related Posts
Promotion

This site uses Google Analytics.