Center align leading icon in Flutter

I need to align hint text and leading icon in the center, like shown here: Center aligned icon and hint

When I add a leading icon, and centre align decoration that is what I get. I need the icon to be in the centre as well.

Leading icon is still left aligned

Edit: Current code

TextField(
      textAlign: TextAlign.center,
    decoration: InputDecoration(
      hintText: 'Type something',
      prefixIcon: Icon(Icons.search)
    )
  ),

Upvotes: 2

Views: 1116

Answers (1)

RuslanBek
RuslanBek

Reputation: 2009

There is a widget for your case: IntrinsicWidth. This widget is used to size its child to the child's intrinsic width.

Output

enter image description here

Full code:


class CenteredTextField extends StatefulWidget {
  const CenteredTextField({Key key}) : super(key: key);

  @override
  _CenteredTextFieldState createState() => _CenteredTextFieldState();
}

class _CenteredTextFieldState extends State<CenteredTextField> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: 40.0,
        margin: EdgeInsets.symmetric(horizontal: 20.0, vertical: 50.0),
        decoration: BoxDecoration(
          color: Colors.orange.withOpacity(0.4),
          borderRadius: BorderRadius.circular(20.0),
          border: Border.all(
            color: Colors.orange,
            width: 1.0,
          ),
        ),
        child: Center(
          child: IntrinsicWidth(
            child: TextField(
              textAlignVertical: TextAlignVertical.center,
              decoration: InputDecoration(
                prefixIcon: Icon(Icons.search),
                hintText: 'Type verse address',
                border: InputBorder.none,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Upvotes: 1

Related Questions