Sub topic 10
Detecting the Platform the Right Way
This chapter assumes basic Dart syntax, Flutter widgets, MaterialApp, Scaffold, and BuildContext. You will learn how to choose a Material or Cupertino variant without tying your widget code to one operating system.
Use `Theme.of(context).platform`
Flutter represents the target platform with the TargetPlatform enum. Its values include android, iOS, macOS, windows, linux, and fuchsia.
Inside a widget, read the platform from the nearest theme:
import 'package:flutter/material.dart';
bool isCupertinoPlatform(BuildContext context) {
final platform = Theme.of(context).platform;
return platform == TargetPlatform.iOS ||
platform == TargetPlatform.macOS;
}This approach uses the widget tree's current configuration. A MaterialApp supplies a ThemeData object, and Theme.of(context) finds that object for the current context.
You can then select a platform-specific widget:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class AdaptiveButton extends StatelessWidget {
const AdaptiveButton({
super.key,
required this.onPressed,
required this.child,
});
final VoidCallback? onPressed;
final Widget child;
@override
Widget build(BuildContext context) {
final platform = Theme.of(context).platform;
final isApplePlatform =
platform == TargetPlatform.iOS || platform == TargetPlatform.macOS;
if (isApplePlatform) {
return CupertinoButton.filled(
onPressed: onPressed,
child: child,
);
}
return FilledButton(
onPressed: onPressed,
child: child,
);
}
}
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: Center(
child: AdaptiveButton(
onPressed: null,
child: Text('Continue'),
),
),
),
),
);
}The widget does not inspect the device directly. It asks Flutter which platform the current theme represents.
Why not use `dart:io`?
A common mistake is to write this:
import 'dart:io';
final isIos = Platform.isIOS;dart:io is unavailable in Flutter web builds. It also makes widget tests less flexible because the operating system is difficult to change during a test. Platform.isIOS can be appropriate for non-UI code that truly needs the host operating system, but it is usually the wrong choice for rendering widgets.
The theme-based approach also supports deliberate overrides:
MaterialApp(
theme: ThemeData(platform: TargetPlatform.iOS),
home: const SettingsPage(),
)This is useful when previewing an iOS design on another computer or testing both branches.
The decision path
| Situation | Preferred source |
|---|---|
| Choosing a widget appearance | `Theme.of(context).platform` |
| Testing a widget branch | `ThemeData(platform: ...)` |
| Non-UI host-specific code | Carefully consider `dart:io` |
Exercise
Why is Theme.of(context).platform usually better than Platform.isIOS for a Flutter widget?
Show answer
It works on web, follows the widget tree's configuration, and can be overridden in tests or previews.