Farwa
Farwa

Reputation: 7024

How to vertically align row items?

Here's my code:

        child: new Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          new Icon(
                              Icons.call
                          ),
                          new Container(
                            height: 30.0,
                            width: 100.0,
                            child: new TextFormField(
                              decoration: new InputDecoration(
                                  labelText: 'User Name'),
                              validator: (val) =>
                              !val.contains('@')
                                  ? 'Not a valid email.'
                                  : null,
                              onSaved: (val) => _email = val,
                            ),

                          )

                        ],

                      ),
                    )

Here Icon and TextFormField isn't vertically aligned. TextFormField gives a margin top to itself and comes a bit down to the phone icon.

Upvotes: 19

Views: 31788

Answers (2)

Dan Field
Dan Field

Reputation: 21641

The problem is that TextFormField is going to add some padding around itself. Since you just want to align the icon, you should probably just add it to your InputDecoration, and you can abandon using a Row entirely; you can also shift it down a bit to force it in line with the text entry bottom underline with some Padding:

new TextFormField(
  decoration: const InputDecoration(
      labelText: 'User Name',
      icon: const Padding(
          padding: const EdgeInsets.only(top: 15.0),
          child: const Icon(Icons.call))),
  validator: (val) =>
      !val.contains('@') ? 'Not a valid email.' : null,
  onSaved: (val) => _email = val,
),

You can skip that Padding if you want it to be aligned the way Flutter thinks it's supposed to be, but I suspect you might still not be happy with it sitting as high as it does by default.

Upvotes: 3

Hemanth Raj
Hemanth Raj

Reputation: 34769

First remove the height property of the Container then set crossAxisAlignment to CrossAxisAlignment.center which aligns the elements of the row to center with respect to vertical axis.

Example:

new Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        new Icon(Icons.call),
        new Container(
          width: 100.0,
          child: new TextFormField(
            decoration: const InputDecoration(labelText: 'User Name'),
            validator: (val) =>
                !val.contains('@') ? 'Not a valid email.' : null,
            onSaved: (val) => _email = val,
          ),
        )
      ],
)

Upvotes: 27

Related Questions