Sub topic 11
Adapting to platform conventions
This chapter assumes you can build widget trees with StatelessWidget and StatefulWidget, read Theme.of(context), and write a basic widget test. The earlier chapters changed the layout based on available space. Here you change how widgets look and behave based on the platform they run on.
Why platform conventions matter
Size is not the only thing that differs between devices. A user on iOS expects a different switch, a different dialog style, a back-swipe gesture and bouncing scroll physics. A user on Android expects Material components and the system back button or gesture. A desktop user expects hover states and menus.
Flutter draws its own pixels, so it does not use native controls by default. Your app looks the same everywhere unless you decide otherwise. Adapting to platform conventions means making a small number of deliberate choices about where the app should follow the host platform.
This is separate from window size. An iPad and an iPhone share a platform but need different layouts. A Pixel tablet and a Pixel phone are both Android but have different window-size classes. Use breakpoints for space and platform checks for conventions.
Detecting the platform
Flutter gives you three ways to ask which platform you are on. They are not interchangeable.
| Source | Returns | Works on web | Respects theme override |
|---|---|---|---|
| `Theme.of(context).platform` | A `TargetPlatform` | Yes | Yes |
| `defaultTargetPlatform` | A `TargetPlatform` | Yes | No (only a debug override) |
| `Platform.isIOS` from `dart:io` | A `bool` | No, it throws | No |
Prefer Theme.of(context).platform. It starts out equal to defaultTargetPlatform, but you can override it with ThemeData(platform: ...). Your tests and previews can then simulate another platform without a device. On the web, defaultTargetPlatform reports the operating system of the browser, so a browser on an iPhone reports TargetPlatform.iOS.
Avoid dart:io for this purpose. Platform.isAndroid throws an UnsupportedError on the web, and it ignores the theme override.
import 'package:flutter/material.dart';
bool isApplePlatform(BuildContext context) {
final platform = Theme.of(context).platform;
return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS;
}Use the `.adaptive` constructors first
Before you write your own platform checks, look for a built-in adaptive widget. Several Material widgets have an .adaptive constructor that renders a Cupertino version when the theme platform is iOS or macOS.
| Widget | Adaptive form | Cupertino result on Apple platforms |
|---|---|---|
| Switch | `Switch.adaptive` | `CupertinoSwitch` |
| Slider | `Slider.adaptive` | `CupertinoSlider` |
| Checkbox | `Checkbox.adaptive` | Rounded Cupertino-style checkbox |
| Progress | `CircularProgressIndicator.adaptive` | `CupertinoActivityIndicator` |
| Dialog | `AlertDialog.adaptive` with `showAdaptiveDialog` | `CupertinoAlertDialog` |
| Icons | `Icons.adaptive.arrow_back`, `Icons.adaptive.share`, `Icons.adaptive.more` | iOS-style glyphs |
These widgets take the same properties as their Material versions. You write the code once and the platform decides how it looks.
import 'package:flutter/material.dart';
class SettingsPage extends StatefulWidget {
const SettingsPage({super.key});
@override
State<SettingsPage> createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
bool _notifications = true;
double _volume = 0.5;
Future<void> _confirmReset() async {
final confirmed = await showAdaptiveDialog<bool>(
context: context,
builder: (context) => AlertDialog.adaptive(
title: const Text('Reset settings?'),
content: const Text('This cannot be undone.'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Reset'),
),
],
),
);
if (confirmed == true && mounted) {
setState(() {
_notifications = true;
_volume = 0.5;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.adaptive.arrow_back),
onPressed: () {},
),
title: const Text('Settings'),
),
body: ListView(
children: [
SwitchListTile.adaptive(
title: const Text('Notifications'),
value: _notifications,
onChanged: (value) => setState(() => _notifications = value),
),
ListTile(
title: const Text('Volume'),
subtitle: Slider.adaptive(
value: _volume,
onChanged: (value) => setState(() => _volume = value),
),
),
ListTile(
title: const Text('Reset'),
onTap: _confirmReset,
),
],
),
);
}
}The dialog actions in this example are Material TextButton widgets, so on iOS the dialog frame is Cupertino but the buttons keep a Material look. If the exact Cupertino button style matters, build the action list with CupertinoDialogAction when isApplePlatform(context) is true.
Deciding what to adapt
Adapting everything means maintaining two apps. Adapt only where a platform convention changes how the user understands or operates the control.
Good candidates for adaptation:
- Toggles, sliders, activity indicators and alert dialogs, because users recognize them by sight.
- Back navigation and page transitions, because they relate to gestures.
- Scroll physics, because bounce on iOS and glow or clamp on Android feel different under the finger.
- Menus on macOS, where
PlatformMenuBarcan place your menu in the system menu bar.
Poor candidates are your brand identity, custom cards and most content layouts. A consistent look across platforms is a legitimate choice.
Scroll physics and page transitions
Scrollable widgets already adapt. The default MaterialScrollBehavior reads the theme platform and picks BouncingScrollPhysics on iOS and macOS, and ClampingScrollPhysics elsewhere. If you set physics explicitly on a list, you override that adaptation, so only do it when you mean to.
Page transitions follow the same pattern. PageTransitionsTheme holds one builder per platform, and the defaults are a slide with swipe-back on iOS and a Material transition on Android. If you want one transition everywhere, set it for each platform you support.
import 'package:flutter/material.dart';
ThemeData buildTheme() {
return ThemeData(
useMaterial3: true,
pageTransitionsTheme: const PageTransitionsTheme(
builders: {
TargetPlatform.android: CupertinoPageTransitionsBuilder(),
TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
TargetPlatform.macOS: CupertinoPageTransitionsBuilder(),
TargetPlatform.windows: CupertinoPageTransitionsBuilder(),
TargetPlatform.linux: CupertinoPageTransitionsBuilder(),
},
),
);
}Choose this deliberately. It gives Android users an iOS-style transition, which some teams want for brand consistency and others avoid.
Testing platform behavior
Because Theme.of(context).platform can be overridden, you can test both branches in a single test file without a device.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
Widget app(TargetPlatform platform) => MaterialApp(
theme: ThemeData(platform: platform),
home: const SettingsPage(),
);
testWidgets('shows a CupertinoSwitch on iOS', (tester) async {
await tester.pumpWidget(app(TargetPlatform.iOS));
expect(find.byType(CupertinoSwitch), findsOneWidget);
});
testWidgets('shows no CupertinoSwitch on Android', (tester) async {
await tester.pumpWidget(app(TargetPlatform.android));
expect(find.byType(CupertinoSwitch), findsNothing);
});
}This test assumes the SettingsPage from earlier is in scope. If you read the platform from defaultTargetPlatform instead of the theme, this override would not reach your code, and you would need debugDefaultTargetPlatformOverride, which is easy to forget to reset.
Common mistakes
- Using
dart:ioon a web build.Platform.isIOSthrows on the web. UseTheme.of(context).platform. - Treating platform as form factor. An iPad is
TargetPlatform.iOS, but it needs a wide layout. Choose layout by window size and conventions by platform. - Reading the platform once at startup. Store nothing global. Read it from the theme in
buildso tests and theme changes work. - Mixing styles by accident. A Cupertino switch inside a Material list is fine, because that is what
.adaptiveproduces. A hand-built Cupertino dialog with Material buttons looks half finished. - Overriding
physicson every list. This turns off the automatic scroll adaptation.
Exercise
A widget test builds your settings page with ThemeData(platform: TargetPlatform.iOS) and expects a CupertinoSwitch. The page uses Switch(...), not Switch.adaptive(...). Does the test pass? Why, and what is the minimal change?
Show answer
The test fails. A plain Switch always renders the Material switch, whatever the theme platform. Only Switch.adaptive (or SwitchListTile.adaptive) reads the theme platform and returns a CupertinoSwitch on iOS and macOS. The minimal change is to replace Switch(...) with Switch.adaptive(...).
Exercise
Why is Theme.of(context).platform better than Platform.isIOS for deciding between two widgets, and when would you still compare the window width instead?
Show answer
Theme.of(context).platform works on every target including the web, and a test or preview can override it through ThemeData(platform: ...). Platform.isIOS throws on the web and cannot be overridden by the theme. Compare the window width when the decision is about available space, such as one pane versus two panes. An iPad and an iPhone share a platform but need different layouts.