Sub topic 8
Safe areas and text scaling
Two settings on a user's device change how much room your layout gets, even when the window size stays the same. System UI such as notches, status bars and gesture bars takes space at the screen edges. The user's font-size setting changes how big your text is. This chapter assumes you know MediaQuery, Scaffold, Row/Column and the constraints model from earlier chapters.
Two kinds of intrusion
A window rarely owns every pixel. Flutter reports the intrusions through MediaQuery:
| Property | Accessor | Meaning |
|---|---|---|
| `padding` | `MediaQuery.paddingOf(context)` | Areas covered by system UI such as the notch, status bar and home indicator. The keyboard reduces it. |
| `viewPadding` | `MediaQuery.viewPaddingOf(context)` | The same system UI areas, but the keyboard does not reduce them. |
| `viewInsets` | `MediaQuery.viewInsetsOf(context)` | Areas fully covered by something temporary, mostly the on-screen keyboard. |
When the keyboard opens, viewInsets.bottom grows. padding.bottom drops to 0 because the keyboard now covers the home indicator area, while viewPadding.bottom keeps its value.
import 'package:flutter/material.dart';
class InsetsDebug extends StatelessWidget {
const InsetsDebug({super.key});
@override
Widget build(BuildContext context) {
final padding = MediaQuery.paddingOf(context);
final insets = MediaQuery.viewInsetsOf(context);
final scaler = MediaQuery.textScalerOf(context);
return Text(
'padding: $padding\n'
'insets: $insets\n'
'14 pt text is drawn at ${scaler.scale(14)}',
);
}
}Use the specific accessors (paddingOf, viewInsetsOf, textScalerOf) and not MediaQuery.of(context). A widget that calls a specific accessor rebuilds only when that one property changes. A widget that calls MediaQuery.of rebuilds when anything changes, including every keyboard animation frame.
SafeArea
SafeArea reads MediaQuery.paddingOf, adds that much padding around its child, and then removes the consumed padding from the MediaQuery below it. Because of the removal, nesting SafeArea widgets does not pad twice.
You can switch each edge on or off with left, top, right and bottom. The minimum parameter sets a floor, so a button can sit 16 pixels above the bottom edge on devices with no gesture bar and still clear the bar on devices that have one.
import 'package:flutter/material.dart';
class InboxScreen extends StatelessWidget {
const InboxScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Inbox')),
body: SafeArea(
top: false, // the AppBar already handles the top inset
minimum: const EdgeInsets.only(bottom: 16),
child: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: 50,
itemBuilder: (context, i) =>
ListTile(title: Text('Message $i')),
),
),
Padding(
padding: const EdgeInsets.all(16),
child: FilledButton(
onPressed: () {},
child: const Text('Compose'),
),
),
],
),
),
);
}
}What already handles insets
Do not wrap everything in SafeArea by reflex. Several widgets already deal with their own edge:
AppBarpads for the status bar.NavigationBarandBottomNavigationBarpad for the bottom gesture area.Scaffoldshrinks its body when the keyboard opens (resizeToAvoidBottomInsetdefaults totrue).- A scrollable whose
paddingisnullapplies the ambientMediaQuerypadding at the ends of its scroll axis. If you setpaddingyourself, that default no longer applies, so add the inset back yourself.
Where insets matter
- Landscape phones. The notch moves to the left or right edge, so side padding becomes non-zero.
- Edge-to-edge Android. Recent Android versions draw apps behind the system bars by default, so top and bottom padding appear on devices that used to report none.
- Desktop and web. Padding is usually zero, so
SafeAreacosts nothing. Keep it in the code anyway, because the same code runs on phones.
Content that scrolls can go behind the system bars on purpose, as long as its first and last items can scroll clear of them. Fixed controls, such as buttons, text and tappable icons, belong inside the safe area.
Text scaling
Users can raise the system font size, often to 200% or more. Flutter multiplies every font size by that setting before drawing. Layouts that looked fine at 100% often break at 200%: text overflows, gets clipped, or pushes buttons off screen.
Read the setting with MediaQuery.textScalerOf(context), which returns a TextScaler. Call scaler.scale(fontSize) to see the final size. The older textScaleFactor property is deprecated because some platforms now scale nonlinearly. For example, large text may grow less than small text. A single multiplier cannot describe that.
Rules that survive large text
- Do not give text containers a fixed height. Use
ConstrainedBox(minHeight: ...)or padding so the container grows with its content. - Let text share a
RowthroughExpandedorFlexible. Otherwise the text takes its natural width and overflows. - Use
Wrapand notRowfor groups of chips or buttons that may need a second line. - Set
maxLinesandoverflowdeliberately on titles that can be arbitrarily long. - Scale non-text elements that sit next to text when they must keep proportion, for example
size: scaler.scale(24)for an icon beside a label. - Avoid
FittedBoxas a general fix. It shrinks large text back down, which cancels the user's setting.
import 'package:flutter/material.dart';
class ProfileTile extends StatelessWidget {
const ProfileTile({super.key, required this.name, required this.subtitle});
final String name;
final String subtitle;
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: const BoxConstraints(minHeight: 72),
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
const CircleAvatar(child: Icon(Icons.person)),
const SizedBox(width: 12),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
style: Theme.of(context).textTheme.titleMedium,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
Text(subtitle),
],
),
),
],
),
),
);
}
}A SizedBox(height: 72) in place of the ConstrainedBox would look identical at 100% and overflow at 200%. That is the most common text-scaling bug.
Clamping, not disabling
Some elements, such as a dense toolbar or a fixed-size badge, cannot absorb unlimited growth. Do not force the scale to 1.0, because that ignores a real accessibility need. Cap it instead. MediaQuery.withClampedTextScaling limits the scale for everything below it:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, child) => MediaQuery.withClampedTextScaling(
minScaleFactor: 1.0,
maxScaleFactor: 2.0,
child: child!,
),
home: const InboxScreen(),
);
}
}The example assumes InboxScreen from earlier in this chapter is in the same file or imported. A clamp at 2.0 serves most users and keeps the worst-case layout predictable. Apply a tighter clamp to a single widget subtree and not to the whole app when only that subtree needs it.
Testing both
Both settings can be faked in widget tests. The first test sets a narrow window and 200% text, then checks that no overflow was reported. Flutter reports overflow as a framework exception, which tester.takeException() returns. The second fakes a 40-pixel top inset and checks that SafeArea moves its child down by that amount. FakeViewPadding values are in physical pixels, so the test sets the device pixel ratio to 1.0 to make them equal to logical pixels.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
// Adjust this import to your package name and file location.
import 'package:my_app/profile_tile.dart';
void main() {
testWidgets('ProfileTile survives 2x text on a narrow window',
(tester) async {
tester.view.physicalSize = const Size(320, 640);
tester.view.devicePixelRatio = 1.0;
tester.platformDispatcher.textScaleFactorTestValue = 2.0;
addTearDown(tester.view.reset);
addTearDown(tester.platformDispatcher.clearAllTestValues);
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: ProfileTile(
name: 'A very long display name that needs several lines',
subtitle: 'Online',
),
),
),
);
expect(tester.takeException(), isNull);
});
testWidgets('SafeArea keeps content below a 40 px top inset',
(tester) async {
tester.view.physicalSize = const Size(400, 800);
tester.view.devicePixelRatio = 1.0;
tester.view.padding = const FakeViewPadding(top: 40);
tester.view.viewPadding = const FakeViewPadding(top: 40);
addTearDown(tester.view.reset);
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: SafeArea(
child: Align(
alignment: Alignment.topLeft,
child: Text('Hi'),
),
),
),
),
);
expect(tester.getTopLeft(find.text('Hi')).dy, 40);
});
}Common mistakes
- Wrapping the whole app in
SafeArea, which leaves a blank band where a background or map could have extended. - Wrapping a screen that has an
AppBarand padding the top again. Passtop: false. - Reading
MediaQuery.of(context).paddingin a deep widget and rebuilding it on every keyboard frame. Use the specific accessors. - Testing only at 1.0 text scale. Make 2.0 a standard case in your layout tests.
Exercise
A card uses SizedBox(height: 80) around a Row containing an avatar and a two-line Text. It looks right normally but shows a yellow-and-black overflow stripe when the user sets the system font to the largest size. What change fixes it, and why is wrapping the Text in FittedBox a poor fix?
Show answer
Replace the SizedBox with ConstrainedBox(constraints: BoxConstraints(minHeight: 80)) plus padding, and put the Text in an Expanded so it wraps within the available width. The card then grows with its content. FittedBox shrinks the text back down to fit, which cancels the user's chosen font size and defeats the purpose of text scaling.
Exercise
A screen has an AppBar and a bottom-pinned button. Which SafeArea edges should you disable, and which MediaQuery property tells you the keyboard is open?
Show answer
Disable the top edge (top: false), because the AppBar already pads for the status bar. Keep the bottom edge so the button clears the gesture bar. MediaQuery.viewInsetsOf(context).bottom is greater than 0 while the keyboard is open.