Sub topic 1
Responsive vs adaptive: what you are designing for
Prerequisites
This chapter assumes you know Dart 3 syntax, including switch expressions. You should be able to build widget trees with StatelessWidget, and you should have used Row, Column, Scaffold and ListView. You should also have run a Flutter app on an emulator, device or desktop target.
Responsive vs adaptive
Responsive design changes the size of a layout to fit the space it receives. A grid that gains columns as the window widens is responsive. Adaptive design changes the structure of a layout. A bottom bar that becomes a side rail on wide screens is adaptive. Most real apps use both, and this chapter focuses on the sizing side.
How Flutter layout works: constraints down, sizes up
Each widget receives constraints from its parent. Constraints are minimum and maximum limits for width and height. The widget picks a size inside those limits and reports it upward. The parent then places the child. Constraints flow down, and sizes flow up.
This model explains many runtime errors. A Column gives its children unbounded height when its own height is unbounded, so placing a Column directly inside a scrolling parent can fail.
Layouts that flex: Expanded, Flexible, Wrap and AspectRatio
Expanded forces a child to fill the remaining space along the main axis of a Row or Column. Flexible lets a child take up to its share without forcing it to fill. Wrap moves children to a new line when they run out of room. AspectRatio sizes its child to a fixed width-to-height ratio.
import 'package:flutter/material.dart';
class SplitBar extends StatelessWidget {
const SplitBar({super.key});
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(flex: 2, child: Container(height: 60, color: Colors.teal)),
Expanded(child: Container(height: 60, color: Colors.amber)),
],
);
}
}The first child receives two thirds of the row, and the second receives one third.
Reading window information with MediaQuery
MediaQuery gives a widget facts about the window and device, such as size and text scale. Call MediaQuery.sizeOf(context) when you need only the size. The widget then rebuilds only when the size changes.
import 'package:flutter/material.dart';
class WidthLabel extends StatelessWidget {
const WidthLabel({super.key});
@override
Widget build(BuildContext context) {
final width = MediaQuery.sizeOf(context).width;
return Text('Window width: ${width.toStringAsFixed(0)}');
}
}> Note: MediaQuery reports the size of the whole window. A widget inside a narrow panel still sees the full window width.
Wait, that line is a block quote, which is not allowed. Restated as a callout below.
Exercise
A Row contains two Expanded children with flex: 1 and flex: 3. What fraction of the row does each child receive?
Show answer
The first child receives one quarter, and the second receives three quarters, because the free space is divided in proportion to the flex values (1 + 3 = 4).