Organize multiple widgets on screen using columns, rows, spacing, and space distribution.
Open this lesson in KodokonA real screen rarely displays a single widget: you need to organize them. That's the job of layout widgets. Column stacks its children vertically, from top to bottom; Row aligns them horizontally, from left to right. Since they accept several children, the parameter is no longer called child but children, and it receives a list: widgets between square brackets [ ], separated by commas.
import 'package:flutter/material.dart';
Widget buildProfile() {
return const Column(
children: [
Icon(Icons.person, size: 48),
Text("Sonia Ben Ali"),
Text("Flutter Developer"),
],
);
}Row works exactly the same way, but horizontally. Its main axis is the width: the mainAxisAlignment parameter chooses how to distribute the children along that axis (center to group them in the middle, spaceBetween to spread them as far apart as possible...). And to slip a simple empty space between two widgets, use SizedBox: an invisible box whose width (width) or height (height) you set.
import 'package:flutter/material.dart';
Widget buildRating() {
return const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.star, color: Colors.amber),
SizedBox(width: 8),
Text("4.8 out of 5"),
],
);
}Padding adds space around its child, so the content doesn't stick to the edges. The amount of space is described with EdgeInsets: EdgeInsets.all(16) puts 16 pixels on all four sides, EdgeInsets.only(left: 8) only on the left, and EdgeInsets.symmetric(horizontal: 12) on the left and right at the same time.
import 'package:flutter/material.dart';
Widget buildQuote() {
return const Padding(
padding: EdgeInsets.all(16),
child: Text("A text with some room around it"),
);
}One last tool: Expanded. Placed among the children of a Row or a Column, it asks its child to take up all the remaining space. In the example below, the gray box keeps its 80 pixels of width, and the teal box stretches to fill the rest of the width, whatever the screen size.
import 'package:flutter/material.dart';
Widget buildProgress() {
return Row(
children: [
Container(width: 80, height: 40, color: Colors.grey),
Expanded(
child: Container(height: 40, color: Colors.teal),
),
],
);
}