Sub topic 1
Layout starts with the widget tree
Prerequisites
You should know Dart classes and named parameters. You should understand StatelessWidget and its build method. You also need a Flutter app that runs on your machine.
Layout starts with the widget tree
Every Flutter screen is a tree of widgets. A parent widget holds children, and those children may hold more children. Layout runs over this tree, so the parent-child structure decides where each element ends up on screen.
How Flutter layout works: constraints down, sizes up
Layout follows one rule. A parent passes box constraints down. These constraints set a minimum and a maximum width and height. The child chooses a size within those limits and reports it up. The parent then positions the child. A child cannot pick any size it wants, and a parent cannot force a size the child refuses.
Row and Column basics
A Row lays out its children horizontally, from left to right. A Column lays them out vertically, from top to bottom. Both take a children list. Unless a parent gives them tight constraints, each one sizes itself to fit its children.
Main axis and cross axis
Each flex widget has two axes. The main axis runs in the direction of the widget. For a Row, that is horizontal. For a Column, it is vertical. The cross axis runs at a right angle to the main axis. For a Row, the cross axis is vertical.
Aligning children with MainAxisAlignment and CrossAxisAlignment
mainAxisAlignment distributes leftover space along the main axis. Its values include start, center, end, and spaceBetween. crossAxisAlignment positions each child across the cross axis. Its values include start, center, end, and stretch.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Demo())));
class Demo extends StatelessWidget {
const Demo({super.key});
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Rating'),
const SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
Icon(Icons.star),
Text('4.8'),
],
),
],
);
}
}Exercise
In the Row above, what changes if you set mainAxisAlignment to MainAxisAlignment.start?
Show answer
The icon and the score move together to the left edge. The free space collects on the right.