Sub topic 15
Testing adaptive widgets with a platform override
This chapter assumes you can write a basic Flutter widget test (testWidgets, pumpWidget, find, expect). It also assumes you have read the chapters on detecting the platform and on building your own adaptive widget. Here you will learn how to make a test run as iOS, Android, or another platform, and how to avoid the errors that usually follow.
Why adaptive code needs its own tests
An adaptive widget has at least two branches. AdaptiveButton returns a CupertinoButton on iOS and macOS and a FilledButton elsewhere. If you only test on a Linux or macOS development machine, one branch can break and nobody notices until a user reports it.
Flutter widget tests do not run on a device. They run on the host machine inside a test harness, and the harness reports TargetPlatform.android by default, whatever your machine is. So an untouched test exercises only the Material branch. You must override the platform on purpose to reach the other branches.
The working model
Adaptive widgets read the platform from one of two places:
Theme.of(context).platform. This isThemeData.platformif you set it. Otherwise it falls back todefaultTargetPlatform.defaultTargetPlatformfrompackage:flutter/foundation.dart. This is the real platform, unless a test setsdebugDefaultTargetPlatformOverride.
The built-in .adaptive constructors and the AdaptiveButton from the previous chapter use the first source. That gives you two ways to override in a test.
| Technique | Scope | Use it when |
|---|---|---|
| `ThemeData(platform: ...)` | One widget tree | You test one widget or one screen |
| `testWidgets(..., variant: TargetPlatformVariant...)` | Whole test, run once per platform | You want the same assertions on many platforms |
| Setting `debugDefaultTargetPlatformOverride` by hand | Until you reset it | Rarely. Prefer a variant, which resets for you |
| `dart:io` `Platform` | Not overridable | Never, in code you want to test |
Technique 1: override through the theme
Wrap the widget under test in a MaterialApp whose theme sets platform. This test file uses a helper so each case stays short. Replace my_app with your package name.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/adaptive_button.dart';
Future<void> pumpButton(
WidgetTester tester,
TargetPlatform platform, {
VoidCallback? onPressed,
}) {
return tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: platform),
home: Scaffold(
body: Center(
child: AdaptiveButton(
onPressed: onPressed,
child: const Text('Go'),
),
),
),
),
);
}
void main() {
final expectedType = <TargetPlatform, Type>{
TargetPlatform.iOS: CupertinoButton,
TargetPlatform.macOS: CupertinoButton,
TargetPlatform.android: FilledButton,
TargetPlatform.fuchsia: FilledButton,
TargetPlatform.linux: FilledButton,
TargetPlatform.windows: FilledButton,
};
for (final entry in expectedType.entries) {
testWidgets('AdaptiveButton on ${entry.key.name}', (tester) async {
await pumpButton(tester, entry.key);
expect(find.byType(entry.value), findsOneWidget);
});
}
testWidgets('Cupertino branch calls onPressed', (tester) async {
var taps = 0;
await pumpButton(tester, TargetPlatform.iOS, onPressed: () => taps++);
await tester.tap(find.text('Go'));
expect(taps, 1);
});
}The loop generates one named test per platform, so a failure message tells you which platform broke. Testing every TargetPlatform value also catches a branch that was written as if (platform == TargetPlatform.iOS) and forgot macOS.
CupertinoButton.filled builds a CupertinoButton, so find.byType(CupertinoButton) matches it.
Technique 2: a platform variant
When the assertions are the same on every platform, a variant is shorter. A TargetPlatformVariant runs the test body once per platform. It sets debugDefaultTargetPlatformOverride before each run and resets it afterwards.
This example tests the built-in adaptive widgets from AdaptiveSettings. It also shows how to handle their infinite animations.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/adaptive_settings.dart';
bool usesCupertino(TargetPlatform p) =>
p == TargetPlatform.iOS || p == TargetPlatform.macOS;
void main() {
final variant = TargetPlatformVariant.all();
testWidgets('adaptive controls match the platform', (tester) async {
final platform = variant.currentValue!;
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: AdaptiveSettings())),
);
expect(
find.byType(CupertinoSwitch),
usesCupertino(platform) ? findsOneWidget : findsNothing,
);
expect(
find.byType(CupertinoActivityIndicator),
usesCupertino(platform) ? findsOneWidget : findsNothing,
);
await tester.tap(find.text('Info'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(
find.byType(CupertinoAlertDialog),
usesCupertino(platform) ? findsOneWidget : findsNothing,
);
expect(
find.byType(AlertDialog),
usesCupertino(platform) ? findsNothing : findsOneWidget,
);
}, variant: variant);
}Other constructors cover narrower sets: TargetPlatformVariant.only(TargetPlatform.iOS), .mobile(), and .desktop(). all() accepts an excluding set.
The variant changes defaultTargetPlatform, which Theme.of(context).platform falls back to. It also reaches code that reads defaultTargetPlatform directly, such as scroll behavior and text selection controls. A ThemeData(platform: ...) override does not.
Common errors
The test ends with an override still set
If you assign debugDefaultTargetPlatformOverride yourself and forget to set it back to null, the test fails with a message that it overrode the value and did not reset it. Use a variant, or reset it in addTearDown.
testWidgets('manual override', (tester) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
addTearDown(() => debugDefaultTargetPlatformOverride = null);
// pumpWidget and expectations here.
});`pumpAndSettle` times out
pumpAndSettle keeps pumping frames until nothing is scheduled. A spinner never stops scheduling frames. That applies to both CircularProgressIndicator.adaptive branches, the Material one and CupertinoActivityIndicator. The call then throws a timeout. In the test above, pump() followed by pump(Duration) lets the dialog finish its 250 ms transition without waiting for the spinner. Use pumpAndSettle only on screens with no looping animation.
Testing `dart:io`
A widget that checks Platform.isIOS from dart:io always reports the host machine. It returns false on a Linux CI runner for every variant, so the Cupertino branch is unreachable. The same code also throws on web. Move the check to Theme.of(context).platform, as covered earlier in this tutorial.
A missing `Material` ancestor
If you pump a Material widget such as TextField or ListTile without a Scaffold or Material above it, you get "No Material widget found". Wrap the widget under test in MaterialApp and Scaffold as the examples above do. For a Cupertino-only screen, use CupertinoApp instead. Without a Theme ancestor, Theme.of returns a fallback theme whose platform is defaultTargetPlatform. So ThemeData(platform: ...) has no effect there, and you need the variant.
Asserting the wrong type
AlertDialog.adaptive on iOS builds a CupertinoAlertDialog, not an AlertDialog. If you assert find.byType(AlertDialog) for every platform, the iOS run fails. Assert on what each platform should produce, as the example does.
Beyond type checks
Finding the right widget type confirms the branch, not the appearance. Two further checks are worth adding for important screens:
- Behavior tests. Tap, type, and toggle, then assert on state, as the
tapscounter does above. Both branches should have the same behavior even though they look different. - Golden tests.
expectLater(find.byType(MyScreen), matchesGoldenFile('my_screen_ios.png'))compares pixels. Use a separate file per platform and run them on one consistent machine, because font rendering differs between operating systems.
Exercise
A teammate's widget chooses CupertinoSwitch when Platform.isIOS (from dart:io) is true. Their widget test sets ThemeData(platform: TargetPlatform.iOS) and expects CupertinoSwitch, but it fails. Why, and what two changes make the widget testable?
Show answer
Platform.isIOS reads the host operating system, which is not iOS on a test machine, and neither ThemeData.platform nor a variant can change it. So the Material branch always runs. Change the widget to read Theme.of(context).platform (or use Switch.adaptive), and then the ThemeData(platform: TargetPlatform.iOS) override, or a TargetPlatformVariant, selects the Cupertino branch.
Exercise
You write await tester.pumpAndSettle() after pumping a screen that contains CircularProgressIndicator.adaptive(), and the test throws a timeout. What do you use instead, and why?
Show answer
Use await tester.pump() (optionally followed by await tester.pump(const Duration(milliseconds: 500))). The spinner animates forever, so pumpAndSettle never reaches a frame with nothing scheduled. pump advances a fixed amount and returns.