In this example, I will share how to align one widget to the top of the screen and center another widget to the middle of the screen in Flutter.
One option is to use an Expanded widget. This widget will expand fill all the space available in the parent, and then you center the child inside it. Note that this only works inside Flex widgets, like Row, Column etc.
In your case, I also recommend removing the screenWidth variable for the row width, and use the Expanded widget to make the container fill the screen horizontally.
This is the final code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | body: Column(children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Expanded( //makes the red row full width child: Container( color: Colors.redAccent, height: 50.0, child: Center( child: Text( "Hello World!", style: TextStyle( fontSize: 18.0, color: Colors.white, ), ), ), ), ), ], ), // This expands the row element vertically because it's inside a column Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ // This makes the blue container full width. Expanded( child: Container( color: Colors.blueAccent, height: 50.0, child: Center( child: Text( "Thanks for the help!", style: TextStyle( fontSize: 18.0, color: Colors.white, ), ), ), ), ), ], ), ), ] ), |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.