Flutter Container Positioning or alignment inside Row widget

Imtiaz Dipto picture Imtiaz Dipto · Nov 9, 2019 · Viewed 7.3k times · Source

I'm new in flutter. right now learning how to positioning or aligning widgets. I have two containers inside my row widget. I want to set my first container(which is red container) at the top left, and also want to set my second container(which is blue container) at the top right. how can I achieve this?

here is code sample :

class MyRow extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.teal,
        body: SafeArea(
          child: Row(
            children: <Widget>[
              Container(
                width: 100.0,
                height: 100.0,
                color: Colors.red,
              ),
              Container(
                width: 100.0,
                height: 100.0,
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Answer

Mohammad Anwer Moin picture Mohammad Anwer Moin · Dec 6, 2019

Flutter has a rich documentation on Layouts, Mr.Tomek Polański has also explain Layouts in details .

You have to understand about Row and Column wise MainAxisAlignment, CrossAxisAlignment,

when you want to position something which has single child, Use FittedBox or ConstrainedBox or SizedBox

as you have multiple children's under the hood of ROW Widget CrossAxisAlignment is your friend use it to achieve your goal.

  1. Wrap your Container under Expanded Widget which will provide you Flex property, it helps you to provide flexibility to your Container. Expanded Widget will also helpful for your Landscape and Portrait Screen Size.
  2. Use SizedBox Widget within your Container Widgets which will provide you in between an invisible spaced Sized Box with maximum width.
  3. I put first Container(Red One) as flex property 1 as well as Second Container(Blue One), it means set 1 times the Size of Row to both of Containers, and double the size to my invisible SizedBox so that our Red Box and BlueBox can fit at the corners Top Left and Top Right.

Here you can see the final Version of the Code.

return Scaffold(
  backgroundColor: Colors.teal,
  body: SafeArea(
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Expanded(
          flex: 1,
          child: Container(
            width: 100.0,
            height: 100.0,
            color: Colors.red,
          ),
        ),
        Expanded(
          flex: 2,
          child: Container(
            width: double.infinity,
          ),
        ),
        Expanded(
          flex: 1,
          child: Container(
            width: 100.0,
            height: 100.0,
            color: Colors.blue,
          ),
        ),
      ],
    ),
  ),
);

enter image description here enter image description here