Sub topic 2
Fixing layout problems and overflow errors
This chapter assumes you know basic Dart syntax and async code, can write StatelessWidget and StatefulWidget classes, can run a Flutter app on a device, and understand the widget tree and the build method. It covers four tasks: fixing layout overflow, logging, pausing code, and finding jank.
Fixing layout problems and overflow errors
An overflow happens when a child widget needs more space than its parent gives it. Flutter then shows a yellow and black stripe and reports a RenderFlex overflow. Select the widget in the Widget Inspector, and the Layout Explorer shows the constraints each parent passes down.
import 'package:flutter/material.dart';
class OverflowDemo extends StatelessWidget {
const OverflowDemo({super.key});
@override
Widget build(BuildContext context) {
return const Row(
children: [
Icon(Icons.info),
Expanded(
child: Text(
'A very long message that does not fit on one line of a narrow screen.',
),
),
],
);
}
}Wrapping the Text in Expanded gives it the remaining width, so the text wraps instead of overflowing.
Logging with dart:developer and the Logging view
Use developer.log to write a message with a name. The Logging view in DevTools can filter by that name.
import 'dart:developer' as developer;
void loadCart(List<String> items) {
developer.log(
'Loaded ${items.length} items',
name: 'cart',
);
}Filter the Logging view by cart to hide messages from other parts of the app.
Pausing code with breakpoints and stepping
Click a line number in the Debugger view to set a breakpoint. When execution pauses, use step over, step into, and step out to move through the code and inspect variables. To pause only when something goes wrong, call debugger with a condition.
import 'dart:developer';
double applyDiscount(double total, double discount) {
final result = total - discount;
debugger(when: result < 0, message: 'Negative total');
return result;
}Finding jank in the Performance view
Jank is a dropped frame. On a 60 Hz display, a frame must finish within about 16 ms. Profile mode removes debug overhead, so run the app with:
flutter run --profileOpen the Performance view, record while you reproduce the problem, and select a red frame bar. The view shows whether build, layout, or paint caused the delay.
Exercise
A Row child overflows on a narrow phone. Which change fixes it, and why?
Show answer
Wrap the Text in Expanded. A Row gives its children unbounded width, so Expanded limits the Text to the space left in the row, and the text wraps.