Sub topic 10
Detecting the platform the right way
This chapter assumes you can build screens with StatelessWidget and StatefulWidget, that you know MaterialApp and Scaffold, and that you have seen BuildContext and Theme.of(context). You don't need to know the Cupertino widgets in detail yet. Here you learn how a Flutter app decides which platform it is running on, which of the available checks to trust, and which to avoid.
Why the question is harder than it looks
Flutter draws every pixel itself, so a widget does not look like an iOS widget unless you ask for one. To choose between a Material and a Cupertino variant, your code has to know the platform. Flutter offers several ways to ask, and they answer slightly different questions:
- What operating system is the process running on?
- Is the code running in a browser?
- Which platform should the framework imitate for this part of the tree?
Mixing these up causes the most common bugs in adaptive code: crashes on web, widget tests that can't reach a branch, and previews that can't show the other platform.
TargetPlatform: the value you want
TargetPlatform is an enum in package:flutter/foundation.dart with six values: android, fuchsia, iOS, linux, macOS and windows. It describes the platform whose conventions the framework should follow. That is usually the real operating system, but it doesn't have to be.
There are two ways to read it:
| Source | Needs a `BuildContext` | Can be overridden for a subtree | Typical use |
|---|---|---|---|
| `Theme.of(context).platform` | Yes | Yes, with `Theme` or `ThemeData(platform: ...)` | Widget `build` methods |
| `defaultTargetPlatform` | No | Only globally, in tests and debug tools | Code with no context, such as services |
Theme.of(context).platform is the preferred choice inside widgets. ThemeData.platform defaults to defaultTargetPlatform, so in a normal app both return the same value. The theme version also respects any override above the widget in the tree. The helper below is the one used throughout this tutorial:
import 'package:flutter/material.dart';
bool isCupertinoPlatform(BuildContext context) {
final platform = Theme.of(context).platform;
return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS;
}The helper treats macOS like iOS. A Flutter app on a Mac should usually use the Apple look, and the Cupertino widgets are designed for both. The other four values fall through to Material.
How the value is chosen
On a device, defaultTargetPlatform comes from the build target. On the web it comes from the browser's user agent. Safari on an iPhone reports TargetPlatform.iOS, and Chrome on a Windows PC reports TargetPlatform.windows. A Flutter web app can therefore adapt to the visitor's platform without any extra code.
Why not dart:io Platform
Many tutorials use Platform.isIOS from dart:io. It works on phones, but it has three problems in a cross-platform app:
dart:iois not available on the web. Importing it in code that compiles for web produces an error, orPlatformthrowsUnsupportedErrorwhen you use it.- It reads the real operating system. A widget test running on your Linux CI machine always sees Linux, so the iOS branch can't be reached.
- It cannot be overridden for a subtree. You can't preview the iOS look inside an Android build.
import 'dart:io' show Platform;
// Avoid: breaks on web and cannot be tested per platform.
bool badIsIos() => Platform.isIOS;Theme.of(context).platform has none of these problems. It works everywhere, it responds to test overrides, and a parent Theme can change it.
kIsWeb answers a different question
kIsWeb from package:flutter/foundation.dart tells you whether the code was compiled for a browser. It does not tell you the operating system. Use it for web-specific behaviour such as links, file pickers, or hiding a "quit" button. Don't use it to pick a design language.
import 'package:flutter/foundation.dart';
String describeEnvironment() {
final where = kIsWeb ? 'browser' : 'native app';
return '$where on ${defaultTargetPlatform.name}';
}This function needs no context. It reports browser on iOS for Safari on an iPhone and native app on android on a phone.
Overriding the platform for a subtree
Because Theme carries the platform, you can change it for part of the tree. This helps for previews, design reviews, and screens that must always use one look:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: PlatformPreview()));
class PlatformPreview extends StatelessWidget {
const PlatformPreview({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for (final platform in [TargetPlatform.android, TargetPlatform.iOS])
Theme(
data: Theme.of(context).copyWith(platform: platform),
child: const PlatformLabel(),
),
],
),
);
}
}
class PlatformLabel extends StatelessWidget {
const PlatformLabel({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Text('Platform: ${Theme.of(context).platform.name}'),
);
}
}Both labels appear on screen at once, whatever device runs the app. PlatformLabel doesn't know it is being overridden. It reads the theme like any other widget.
The override changes what Theme.of(context).platform returns. It doesn't change the operating system. Behaviour tied to the real device, such as the keyboard layout, system fonts, or haptics, is unaffected. Scroll physics, text selection controls and page transitions follow ThemeData.platform, so those do change.
Overriding the platform in tests
In widget tests you have two options. The first is to set platform on the ThemeData of the app under test. The final chapters of this tutorial use that approach. The second is to set the global value. Use it when the code under test reads defaultTargetPlatform directly:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('reads the overridden default platform', (tester) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
try {
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) =>
Text(Theme.of(context).platform.name),
),
),
);
expect(find.text('iOS'), findsOneWidget);
} finally {
debugDefaultTargetPlatformOverride = null;
}
});
}The finally block matters. The test framework fails a test that leaves the override set, and a leaked override would also change every test that runs afterwards. For running one test body on several platforms, flutter_test provides TargetPlatformVariant, which sets and clears the override for you:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets(
'platform is one of the chosen targets',
(tester) async {
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) =>
Text(Theme.of(context).platform.name),
),
),
);
final text = tester.widget<Text>(find.byType(Text)).data;
expect(['iOS', 'android'], contains(text));
},
variant: TargetPlatformVariant({TargetPlatform.iOS, TargetPlatform.android}),
);
}Common mistakes
- Checking
Platform.isIOSinside a widget. It breaks web builds and can't be tested. UseTheme.of(context).platform. - Calling
Theme.of(context)where no theme exists. In an app built onCupertinoApp, there is no MaterialThemeabove your widgets, soTheme.ofreturns a default theme whose platform isdefaultTargetPlatform. That works, but it ignores any platform you set elsewhere. - Forgetting macOS. Checking only
TargetPlatform.iOSgives Mac users the Material look. - Branching on
kIsWebto choose a look. A web page opened on an iPhone is still an iPhone. - Reading the platform once and caching it. A parent
Themecan change the value, so read it inbuild.
Choosing a check
Use this rule of thumb:
- In a widget's
build, readTheme.of(context).platform. - Outside the widget tree, with no context, read
defaultTargetPlatform. - For browser-only behaviour, use
kIsWeb. - Reserve
dart:ioPlatformfor code that never compiles for web and truly needs the real operating system, such as reading environment variables.
Exercise
A teammate writes if (Platform.isIOS) return CupertinoSwitch(...) inside a widget. Name two problems with this and give the replacement.
Show answer
First, dart:io is unavailable on web, so the app fails to build or throws at runtime in a browser. Second, it reads the real operating system, so a widget test on a Linux machine can never reach the iOS branch and a parent Theme can't override it. Replace it with final platform = Theme.of(context).platform; and compare against TargetPlatform.iOS and TargetPlatform.macOS.
Exercise
Your test sets debugDefaultTargetPlatformOverride = TargetPlatform.iOS and then an assertion fails. Why should the reset to null be in a finally block, and what is an alternative that avoids manual resets?
Show answer
If the assertion throws, code after it never runs, so the override stays set. The framework reports an error for the leaked override, and later tests would run with the wrong platform. A finally block always clears it. The alternative is variant: TargetPlatformVariant.only(TargetPlatform.iOS) on testWidgets, which sets and clears the override automatically.