Sub topic 12
Building your own adaptive widget
This chapter assumes you know StatelessWidget and StatefulWidget, BuildContext, and the basics of MaterialApp. You should also have read the earlier chapters on Cupertino controls and on detecting the platform with Theme.of(context).platform. Here you will wrap a platform choice in one reusable widget so that screens never repeat the check.
Why write your own adaptive widget
Flutter ships .adaptive constructors such as Switch.adaptive. They cover only some widgets. There is no adaptive filled button, no adaptive list row, and no adaptive app bar. When you need one of those, you write the branch yourself.
The tempting approach is to put an if at every call site. That fails in three ways:
- The same check is copied across many screens, so a change must be made in many places.
- Screens fill up with platform logic that hides what they actually do.
- The two variants drift apart. One gets a new parameter and the other does not.
A custom adaptive widget fixes this. It has one public API, one place that decides the platform, and one place to edit when the design changes.
The shape of an adaptive widget
An adaptive widget follows a fixed recipe:
- Expose the parameters both variants understand, such as
onPressedandchild. - Read the platform from
Theme.of(context).platforminsidebuild. - Return the Cupertino widget or the Material widget.
Here is the helper from the platform detection chapter:
import 'package:flutter/material.dart';
bool isCupertinoPlatform(BuildContext context) {
final platform = Theme.of(context).platform;
return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS;
}It reads the platform from the theme. It does not use dart:io. The theme value works on the web, where dart:io is unavailable, and tests can override it.
Now use the recipe to build a button:
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;
if (platform == TargetPlatform.iOS || platform == TargetPlatform.macOS) {
return CupertinoButton.filled(onPressed: onPressed, child: child);
}
return FilledButton(onPressed: onPressed, child: child);
}
}A screen now writes AdaptiveButton(onPressed: save, child: Text('Save')). It never mentions Cupertino or Material.
Both variants accept a nullable onPressed. Passing null disables the button on either platform, so the adaptive widget keeps that behavior without extra code.
Choose the shared API carefully
The hard part is not the if. It is deciding which parameters the wrapper accepts. The two libraries differ, and your API must fit both.
| Concern | Material variant | Cupertino variant |
|---|---|---|
| Filled button | `FilledButton` | `CupertinoButton.filled` |
| Padding | `style` with `ButtonStyle` | `padding` parameter |
| Color | `style` or theme | `color` parameter or theme |
| Disabled look | Derived from the theme | `disabledColor` parameter |
If you expose style: ButtonStyle, the Cupertino branch cannot use it. If you expose padding, you must map it to ButtonStyle.padding on one side and to padding on the other. Follow these rules:
- Expose only parameters that both variants can honor.
- Prefer semantic parameters, such as
isDestructive, over visual ones, such ascolor. Each branch then maps the meaning to its own look. - Leave out parameters you do not need. You can add them later.
Here is a version with a semantic isDestructive flag:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class AdaptiveTextAction extends StatelessWidget {
const AdaptiveTextAction({
super.key,
required this.onPressed,
required this.child,
this.isDestructive = false,
});
final VoidCallback? onPressed;
final Widget child;
final bool isDestructive;
@override
Widget build(BuildContext context) {
final platform = Theme.of(context).platform;
if (platform == TargetPlatform.iOS || platform == TargetPlatform.macOS) {
return CupertinoButton(
onPressed: onPressed,
color: null,
child: DefaultTextStyle.merge(
style: TextStyle(
color: isDestructive ? CupertinoColors.destructiveRed : null,
),
child: child,
),
);
}
return TextButton(
onPressed: onPressed,
style: isDestructive
? TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.error,
)
: null,
child: child,
);
}
}The caller says "this action is destructive". Each platform decides how to show that.
Reuse the built-in adaptive widgets
Do not rebuild what Flutter already adapts. Inside your own widget, call the existing .adaptive constructors for the parts they cover, and branch manually only for the rest. A settings row can combine both:
import 'package:flutter/material.dart';
class AdaptiveSwitchRow extends StatelessWidget {
const AdaptiveSwitchRow({
super.key,
required this.label,
required this.value,
required this.onChanged,
});
final String label;
final bool value;
final ValueChanged<bool>? onChanged;
@override
Widget build(BuildContext context) {
return ListTile(
title: Text(label),
trailing: Switch.adaptive(value: value, onChanged: onChanged),
);
}
}Switch.adaptive already picks the platform look, so this row needs no branch of its own. The row is stateless on purpose. The parent owns value and updates it in onChanged, as with any Flutter control.
Pitfalls
Missing imports and widget name clashes
An adaptive widget usually imports both material.dart and cupertino.dart. Both libraries export many shared names, and Flutter re-exports the common ones, so this normally compiles. If a name is truly ambiguous, hide it from one import:
import 'package:flutter/cupertino.dart' hide RefreshCallback;
import 'package:flutter/material.dart';Use hide only when the compiler reports an ambiguity.
Missing ancestors
Cupertino widgets need less from the tree than Material ones, but some Material widgets need a Material ancestor. ListTile is an example. If you place AdaptiveSwitchRow in a CupertinoApp without a Material widget above it, ListTile fails with a "No Material widget found" error. Material ink effects need that ancestor. Either wrap that part of the tree in a Material widget or use CupertinoListTile in the Cupertino branch.
Calling `Theme.of` in a Cupertino-only tree
Under CupertinoApp there is no MaterialApp, but Theme.of(context) still returns a default ThemeData. Its platform comes from the real device, so detection still works. It does not reflect a platform override that you set on a CupertinoApp, because that app has no ThemeData. If you use only CupertinoApp, you can read defaultTargetPlatform instead. For apps based on MaterialApp, which is the common setup in this tutorial, Theme.of(context).platform remains the right source.
Duplicated state
Do not hold the value inside the adaptive widget when a parent could hold it. Keep the widget stateless and pass value and onChanged down. Two variants with separate internal state can lose the value when the platform changes, for example in a test that switches the override.
Make the widget testable
Because the choice depends on ThemeData.platform, a test can select each branch without a device. This test checks both branches of AdaptiveButton:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'adaptive_button.dart';
void main() {
testWidgets('uses CupertinoButton on iOS', (tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.iOS),
home: Scaffold(
body: AdaptiveButton(onPressed: () {}, child: const Text('Go')),
),
),
);
expect(find.byType(CupertinoButton), findsOneWidget);
});
testWidgets('uses FilledButton on Android', (tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(
body: AdaptiveButton(onPressed: () {}, child: const Text('Go')),
),
),
);
expect(find.byType(FilledButton), findsOneWidget);
});
}If the widget read dart:io Platform instead, both tests would run on the host machine and one of them would fail. The theme override is what makes the test possible. The next chapters cover testing in more detail.
Design checklist
Before you add an adaptive wrapper, check these points:
- Does a built-in
.adaptiveconstructor already do this? - Do both variants support every parameter you expose?
- Is the state held by the parent?
- Does each variant have the ancestors it needs, such as
Material? - Does a test cover each branch?
Exercise
You write AdaptiveTextAction and expose a color parameter of type Color. A teammate asks why you would prefer an isDestructive flag instead. Give one reason, and say how a Cupertino branch could handle the flag.
Show answer
A semantic flag states the intent and lets each platform choose its own look. A raw color forces every call site to pick colors that suit both iOS and Material, and it bypasses the theme, which breaks dark mode and brand changes. The Cupertino branch can map isDestructive to CupertinoColors.destructiveRed for the text color, while the Material branch maps it to Theme.of(context).colorScheme.error.
Exercise
Write an AdaptiveProgress widget with no parameters that shows a spinner. It should use the iOS look on iOS and macOS and the Material look elsewhere. What is the shortest correct implementation, and why does no manual if appear?
Show answer
class AdaptiveProgress extends StatelessWidget { const AdaptiveProgress({super.key}); @override Widget build(BuildContext context) => const CircularProgressIndicator.adaptive(); }. No if is needed because CircularProgressIndicator.adaptive reads the platform from the theme and chooses CupertinoActivityIndicator or the Material spinner itself.