Reactivity and Platform-Specific Considerations
Reactivity and Platform-Specific Considerations
The differences between each of these platforms are sometimes subtle and other times extreme. That means that we must be smart about how we build applications, ensuring they will work flawlessly on every platform we plan to target. There are a variety of different techniques we can employ to ensure that our app looks, feels, and acts as it belongs on whatever screen it is running on. In this chapter, we are going to explore these techniques.
Chapter overview
Structure
- Building responsive layouts
- Benefits and limitations of dart:io
- App icons and splash screens
- Material, Cupertino, Yaru, and Fluent UI (oh my!)
- Platform-specific navigation paradigms
- Using packages to build cross-platform UIs
Objectives
Runnable example
dart:io file browser, the two tab bars and the flutter_platform_widgets demos are also available as a runnable project with tests in examples/flutter_for_jobseekers_ch10/. The code on this page is shown as the book prints it, with conversion glitches fixed.Building responsive layouts
Users will run your application on whatever device they have. Perhaps it is the latest iPhone, last year's Android device, a foldable phone, a Web browser on their laptop, or as a Linux desktop application. What works on a phone does not necessarily work on the desktop or in a Web browser. In such cases, it is appropriate to build a different layout. A hamburger menu or tab bar design might work well on the phone, but a different navigation paradigm is appropriate otherwise. So, how do we decide what sort of navigation paradigm to show?
For this, we will use the LayoutBuilder widget. Take the following simple example:
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Center(
child: AnimatedCrossFade(
firstChild: const Text('This is a wide-screen layout'),
secondChild: const Text('This is a small-screen layout'),
crossFadeState: constraints.maxWidth > 600
? CrossFadeState.showFirst
: CrossFadeState.showSecond,
duration: const Duration(milliseconds: 500),
),
);
},
),
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch10/lib/responsive/cross_fade.dart
In this example, we will show different text based on the width of the application. Go ahead and try it out: run it as a desktop or Web application, then resize the window. You will see that as soon as you make the screen narrow or wide enough, the text will cross-fade. Let us look at the scenarios in which LayoutBuilder will update its children:
First layout
New constraints
Parent update
Dependencies
In short, the builder will run when the constraints or dependencies of the child widget update. This useful widget is perfect for building layouts based on different screen sizes.
Different navigation per screen size
Let us look at our example of building different navigation styles. On mobile, we want a hamburger menu but on larger screens, we might want a vertical navigation bar on the edge of the screen. First, build your separate navigation options:
class DesktopNavigation extends StatelessWidget {
final Widget body;
const DesktopNavigation({super.key, required this.body});
@override
Widget build(BuildContext context) {
final double height = MediaQuery.of(context).size.height;
final double width = MediaQuery.of(context).size.width;
return SizedBox(
height: height,
width: width,
child: Row(
children: [
Container(
width: 200,
height: height,
color: Colors.grey,
child: Column(
children: const [
Text('Desktop Navigation'),
],
),
),
body,
],
),
);
}
}
class MobileNavigation extends StatelessWidget {
final Widget body;
const MobileNavigation({super.key, required this.body});
@override
Widget build(BuildContext context) {
return SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: body,
);
}
}
Then you can use a LayoutBuilder to choose which navigation option to use:
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
final double width = MediaQuery.of(context).size.width;
return Scaffold(
appBar: (width <= 600) ? AppBar() : null,
drawer: (width <= 600)
? const Drawer(child: Text('Mobile Navigation'))
: null,
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return constraints.maxWidth > 600
? const DesktopNavigation(
body: Text('This is a wide-screen layout'),
)
: const MobileNavigation(
body: Text('This is a small-screen layout'),
);
},
),
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch10/lib/responsive/navigation.dart
Reactive widgets of any size
Not only will the navigation style change, but we also have control over what widgets are displayed in the app body. It is also possible to nest a LayoutBuilder within another LayoutBuilder. In our example here, we are passing different widgets into the body of the application. This is not strictly necessary, though. Since widgets themselves can have a LayoutBuilder, and we know that the LayoutBuilder can be nested, we can design the smallest of widgets to be reactive. Let us look at an example where we change the placement of a button's label based on the layout:
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return constraints.maxWidth > 600
? Row(
children: const [
MyButton(),
Text('Wide layout'),
],
)
: Column(
children: const [
MyButton(),
Text('Narrow layout'),
],
);
},
),
);
}
}
class MyButton extends StatelessWidget {
const MyButton({super.key});
@override
Widget build(BuildContext context) {
return IconButton(
onPressed: () {},
icon: const Icon(Icons.flutter_dash),
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch10/lib/responsive/button_label.dart
Building navigation from an enum
In instances such as this, you may wish to define your navigation options as an enum, with whatever properties you need to properly navigate to a particular area of your application. Then, the enum itself can be passed into a builder which dynamically builds your navigation system. Look at the following example:
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return constraints.maxWidth > 600
? const WideNavigation(
navigationTargets: NavigationOption.values,
)
: const NarrowNavigation(
navigationTargets: NavigationOption.values,
);
},
),
);
}
}
enum NavigationOption {
home(Home()),
settings(Settings()),
preferences(Preferences());
const NavigationOption(this.target);
final Widget target;
}
From here, you can see how you could easily build a dynamic navigation system using the list of enum values provided. Maybe you would want to use a ListView:
class WideNavigation extends StatelessWidget {
final List<NavigationOption> navigationTargets;
const WideNavigation({super.key, required this.navigationTargets});
@override
Widget build(BuildContext context) {
return ListView(
children: List<Widget>.generate(
NavigationOption.values.length,
(index) => ListTile(
title: Text(NavigationOption.values[index].name),
onTap: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (BuildContext context) =>
NavigationOption.values[index].target,
),
),
),
),
);
}
}
WideNavigation ignores the navigationTargets it is given and reads NavigationOption.values instead, so passing it a shorter list changes nothing. Use navigationTargets.length and navigationTargets[index], as the runnable copy does. The book does not print NarrowNavigation or the Home, Settings and Preferences widgets; the runnable copy assembles them, with NarrowNavigation as a hamburger menu built from the same list.Runnable copy: examples/flutter_for_jobseekers_ch10/lib/main.dart
Benefits and limitations of dart:io
There exists a package, dart:io, which can perform absolute magic… on most of your build targets. Let us look at this package, why it is useful, and when it cannot be used.
dart:io is not a package that you add to pubspec.yaml, but one of Dart's core libraries, which you import with import 'dart:io';. Dart's documentation calls it "the dart:io library" (Dart, n.d.).The dart:io package is a library that deals with:
Files and directories
Processes
Sockets and WebSockets
HTTP clients and servers
If your application needs to do any of these, you will likely be using dart:io. That is a long list of accomplishments for one small package, so let us break it down and look at how some of these can be helpful.
Listing a directory
Let us start with files and folders. Specifically, let us list all the files and folders in a given directory:
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
const String path = "/";
final Directory directory = Directory(path);
return Scaffold(
body: FutureBuilder(
future: listDirectoryContents(directory),
builder: (
BuildContext context,
AsyncSnapshot<List<FileSystemEntity?>> snapshot,
) {
if (snapshot.hasError) {
return const Text('There was an error.');
}
if (!snapshot.hasData) {
return const Text('There was no data');
}
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext context, int index) {
final FileSystemEntity file = snapshot.data![index]!;
final String filename = file.path.split(path)[1];
if (file is File) {
return Text(
'📄 $filename',
);
}
if (file is Directory) {
return Text(
'📁 $filename',
);
}
return const SizedBox();
},
);
},
),
);
}
Future<List<FileSystemEntity>> listDirectoryContents(Directory dir) {
final List<FileSystemEntity> files = <FileSystemEntity>[];
final Completer<List<FileSystemEntity>> completer =
Completer<List<FileSystemEntity>>();
final Stream<FileSystemEntity> lister = dir.list(recursive: false);
lister.listen(
(file) async => files.add(file),
onError: (Object e) => log('$e'),
onDone: () => completer.complete(files),
);
return completer.future;
}
}
build(), which the FutureBuilder documentation rules out: "It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted" (flutter/flutter, n.d.-a). The runnable copy is a StatefulWidget that creates the future once, in initState(); its tests show that a rebuild does not list the directory again. The code also needs import 'dart:async'; (Completer), import 'dart:developer'; (log) and import 'dart:io';.Reading a file
This is only possible by leveraging the power of dart:io and its ability to read files and list directory contents. Let us expand this example further so that we can print out the contents of files that we can read. First, let us update the widget to read the contents of the file using a method we will create in a moment. We already have the ability to list the directory contents, so we can re-use that code:
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
const String path = "/";
final Directory directory = Directory(path);
return Scaffold(
body: FutureBuilder(
future: listDirectoryContents(directory),
builder: (
BuildContext context,
AsyncSnapshot<List<FileSystemEntity?>> snapshot,
) {
if (snapshot.hasError) {
return const Text('There was an error.');
}
if (!snapshot.hasData) {
return const Text('There was no data');
}
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext context, int index) {
final FileSystemEntity file = snapshot.data![index]!;
final String filename = file.path;
if (file is File) {
return TextButton(
style: const ButtonStyle(
alignment: Alignment.centerLeft,
),
onPressed: () async {
final String? contents = await readFile(File(filename));
if (contents != null) {
log(contents);
}
},
child: Text('📄 $filename'),
);
}
if (file is Directory) {
return Text('📁 $filename');
}
return const SizedBox();
},
);
},
),
);
}
}
Next, we can create the method we will use to read the contents of the file. Note that this code exists within our widget, just like our listDirectoryContents method:
Future<String?> readFile(File file) async {
String? fileContents;
try {
fileContents = await file.readAsString();
} catch (e) {
log('Unable to read file contents');
return null;
}
return fileContents;
}
Now, we can tap on any file in the directory listing to log its contents to the debug console.
Runnable copy: examples/flutter_for_jobseekers_ch10/lib/file_browser.dart (this version, with listDirectoryContents and readFile in the widget's State; see the correction above)
Writing a file
We can just as easily write to a file:
final File logFile = File('log.txt');
IOSink sink = logFile.openWrite();
sink.write('FILE ACCESSED ${DateTime.now()}\n');
await sink.flush();
await sink.close();
And if you do not want to completely overwrite the contents of the file you are writing to:
IOSink sink = logFile.openWrite(mode: FileMode.append);
Or if you are trying to write binary data (such as an image or some other type of data), use the following:
sink.add(List<int> data);
sink.add(List<int> data); is the method's signature, not a call, and does not compile; call it with your bytes, for example sink.add(data); where data is a List<int>. The awaits only work inside an async function. And File('log.txt') is relative to the process's current directory, which is not a location you choose in a mobile or desktop app; Flutter's Read and write files recipe instead says to "combine the path_provider plugin with the dart:io library" to find the correct local path (Flutter, n.d.). The runnable copy's writeLog takes the file as a parameter.The catch: no dart:io on the Web
We can list files and directories, read file contents, and write files, among many other operations by using dart:io, so what is the catch? It turns out, dart:io is only available on non-Web platforms.
dart:io, we are strictly limited in where we can deploy it.This is still true: "Only non-web Flutter apps, command-line scripts, and servers can import and use dart:io, not web apps" (Dart, n.d.).
image_picker_for_web, which is only available for the Web. When deciding the functionality of your application, it is important to explore the packages that you will be using to build said application. If the packages you want to use will not support a platform you want to target, it is important to understand that early in the process.App icons and splash screens
Branding your application with an appealing app icon (see Figure 10.1) and splash screen is a vital finishing touch for every application. Each platform is a bit different, with varying requirements. Let us start with the app icon requirements, then we will talk about how to implement them before moving on to a splash screen:

Figure 10.1: Flutter's default app icon on Android
App icon guidelines
The app icon requirements change from time to time as Google, Microsoft, Apple, and others update their design guidelines. It is important to stay informed about these design guideline changes so your app does not feel old or out of place to users. Here are some links to the app icon guidelines for various platforms:
Replacing the icon files
After you have designed an icon, you will need to tell each native platform you are targeting how to find your image. The official Flutter docs are useful in this, as they offer some additional guidance. You can find them here: https://docs.flutter.dev/ui/assets/assets-and-images#updating-the-app-icon (the book's https://docs.flutter.dev/development/ui/assets-and-images#updating-the-app-icon redirects there).
Fortunately for us, Flutter includes default app icons. By simply overwriting the existing files while maintaining the same filename, our icons will be updated automatically:
Windows
Navigate to the windows\runner\resources directory where you will find the app_icon.ico file. If you do not know how to create a .ico file, a quick online search ought to point you in the right direction (keywords: png to ico or jpg to ico should suffice).
macOS
Look in the macos/Runner/Assets.xcassets/AppIcon.appiconset directory.
Web
Look in the web directory for the favicon.png file. There are also additional icons of larger sizes in the icons subdirectory, which you will want to update.
macos/Flutter/Runner/Assets.xcassets/AppIcon.appiconset. A project created by flutter create (Flutter 3.29) has it at macos/Runner/Assets.xcassets/AppIcon.appiconset; the macos/Flutter directory holds the generated Flutter configuration, not the Runner.Provided you choose not to rename your app icon files, no further configuration is required.
flutter_launcher_icons package. The documentation is quite straightforward and easy to follow, with plenty of examples in the git repository. Be sure to check this package out when it comes time to set your icons!Splash screens
Let us look at splash screens next. Like before, here are some resources for designing splash screens on various platforms:
Desktop (Windows/macOS)
The requirements for each platform are as different as the app icon requirements, so reading over the documentation for the platform(s) you are targeting is mandatory:
iOS
LaunchScreen.storyboard, which can be customized any way you choose in Xcode.Android
AndroidManifest.xml file to configure the activity style, which is what defines the look and feel of the splash screen. In addition to this, you will also be modifying the styles.xml file, which is where the styles are defined. Then, you will likely be creating image assets that the style refers to.The Flutter documentation has instructions on what to modify for each platform, here: https://docs.flutter.dev/development/ui/advanced/splash-screen.
flutter_native_splash package is highly configurable, allowing platform-specific configurations in addition to a global configuration. The configuration lives in pubspec or a separate, custom configuration file. Once configured, you can run the plugin from the command line to automatically generate the splash screens for you. This is a much easier way to implement a splash screen, so be sure to check out the package.Material, Cupertino, Yaru, and Fluent UI (oh my!)
By now, you are familiar with both Material and Cupertino widgets. If you need a refresher, look way back in Chapter 5: Handling User Input at some of the difference between Material and Cupertino input widgets. These widgets are great for Android and iOS/macOS development, but did you know that they are not the only styles available to us?
Yaru (Ubuntu)
If you have ever used Ubuntu Linux, you will be familiar with the Yaru style. Look at the screenshot to see how this style differs from Material and Cupertino (Figure 10.2).

Figure 10.2: Yaru (Ubuntu) styled widgets
The Yaru package works by wrapping your MaterialApp widget with a YaruTheme widget, which has a builder that provides the appropriate themes for you to use in your MaterialApp. After importing the Yaru package, the setup is quite simple:
YaruTheme(
builder: (context, yaru, child) {
return MaterialApp(
theme: yaru.theme,
darkTheme: yaru.darkTheme,
home: Scaffold(
appBar: AppBar(
title: Text('Yaru Theme'),
),
body: Container(),
),
);
}
);
Adwaita (Gnome)
Maybe Yaru is not your style, though. Perhaps you prefer the Gnome desktop's Adwaita style (Figure 10.3). There is certainly a package for that, too. Look no further than libadwaita. This package comes with replacement widgets, rather than a theme, however.

Figure 10.3: The Gnome Adwaita style
If you prefer Yaru's method of building a theme rather than replacing the widgets, try out the adwaita package. The setup is similar in that it builds a theme; however, it requires you to create a ValueListenableBuilder widget, instead:
class MyApp extends StatelessWidget {
final ValueNotifier<ThemeMode> themeNotifier = ValueNotifier(
ThemeMode.light
);
MyApp({super.key});
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<ThemeMode>(
valueListenable: themeNotifier,
builder: (_, ThemeMode currentMode, __) {
return MaterialApp(
theme: AdwaitaThemeData.light(),
darkTheme: AdwaitaThemeData.dark(),
debugShowCheckedModeBanner: false,
home: MyHomePage(themeNotifier: themeNotifier),
themeMode: currentMode,
);
},
);
}
}
Here is what the adwaita package looks like once you have got it all set up (Figure 10.4):

Figure 10.4: Material widgets styled using the Adwaita package
builder and AdwaitaThemeData.light() / .dark() shown above still match the current releases of the packages (yaru 12.0.0 and adwaita 1.1.0, checked on 2026-11-16). MyHomePage is the app's own home screen, not part of the package.Fluent UI (Windows)
These styles are all beautiful, clean, concise, and easy to use. However, they only truly feel at home on a Linux desktop. If you are targeting a Windows environment, you will probably want something that feels more at home by using Microsoft's Fluent style.
Microsoft has published the Fluent design guidelines for developers to use when creating applications on the Windows platform. You can find the documentation here: https://docs.microsoft.com/en-us/windows/uwp/design. This style has been in use for the past couple of versions of Microsoft Windows and does not appear to be going anywhere any time soon.
The package fluent_ui is an unofficial implementation of the Fluent design system, based on the official documentation. Check out the showcase to see what kind of widgets are available, what they look and feel like, and what their Material-equivalent widget is. You can find the showcase here: https://bdlukaa.github.io/fluent_ui/. Here is a sampling of what is on offer (Figure 10.5):

Figure 10.5: A selection of widgets available in the Fluent UI package
macos_ui (macOS)
These widgets will feel right at home on a Windows computer. There is even a very similar package for macOS, called macos_ui. Check out the showcase screenshot (Figure 10.6) and then look at the gallery for yourself here: https://groovinchip.github.io/macos_ui/#/.

Figure 10.6: macOS style widgets from the macos_ui package
Platform-specific navigation paradigms
We have all used software on computer, on the Web, and on our phones. There are certain navigation paradigms used on each platform that meet an agreed-upon standard:
Web
Desktop
Mobile
The back button
The differences do not stop there, however. Let us look, specifically, at an Android/iOS paradigm: the back button. Since its inception, Android has had a universal back button, starting first as a hardware key (Figure 10.7), later as a software button, and eventually as a gesture:

Figure 10.7: Note the hardware back button on the HTC Desire, circa 2010. Source: Wikipedia
Android
iOS
Now, we are not here to start a culture war. The Android versus iOS debate has been raging since 2009 and is not likely to end any time soon. The fact is, if you are an iOS user, you probably do not even notice the inconsistencies in navigation styles from app to app. And if you are on Android, you do not think twice about reaching for that universal back button or gesture.
Stacked navigation in tab views
iOS has another paradigm that does not exist on Android: stacked navigation in tab views. The tab bar can be found both on iOS (Figure 10.8) and Android (Figure 10.9):

Figure 10.8: An example of the iOS tab bar. Source: Apple

Figure 10.9: An example of a Material Design style tab bar. Source: Google
Ok, strictly speaking, the paradigm can exist. In practice, you generally will not find it, though. So, what are we talking about when we say, stacked navigation? To answer that, let us look at a couple of code examples. First, let us examine a typical tab bar using BottomNavigationBar, part of the Material package:
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
static const List<Widget> _widgetOptions = <Widget>[
Text('Home'),
Text('Business'),
Text('School'),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.purple[800],
onTap: _onItemTapped,
),
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch10/lib/tabs/material_tabs.dart
When you tap a tab (onTap: _onItemTapped, line 46 in the book), the body of the Scaffold updates by building a new widget (child: _widgetOptions.elementAt(_selectedIndex), line 27). The widget, which was previously the body of the Scaffold, is disposed of and a new widget is built. As we know, when a widget is disposed of, so is its state. If the widget that is being used as the body of the Scaffold contains a navigation stack of its own, that navigation stack will be disposed of, too.
Now, let us look at the CupertinoTabScaffold, CupertinoTabBar, and CupertinoTabView to see how it differs:
class CupertinoTabBarApp extends StatelessWidget {
const CupertinoTabBarApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
home: CupertinoTabBarExample(),
);
}
}
class CupertinoTabBarExample extends StatelessWidget {
const CupertinoTabBarExample({super.key});
@override
Widget build(BuildContext context) {
return CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.star_fill),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.clock_solid),
label: 'Recents',
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.person_alt_circle_fill),
label: 'Contacts',
),
],
),
tabBuilder: (BuildContext context, int index) {
return CupertinoTabView(
builder: (BuildContext context) {
return Center(
child: Text('Content of tab $index'),
);
},
);
},
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch10/lib/tabs/cupertino_tabs.dart
These three widgets work in conjunction to create something a bit different. The CupertinoTabBar works just like the BottomNavigationBar, but the CupertinoScaffold differs from the Scaffold in one key aspect: there is a tabBuilder. Since each tab is built via the CupertinoTabScaffold, they are not disposed of or replaced when a new tab is tapped. The state of the tab's body widget is retained, thereby allowing you to navigate deep into each tab's screens, switch to a different tab, then back to the first without losing your navigation stack.
CupertinoScaffold" should read CupertinoTabScaffold; Flutter has no CupertinoScaffold widget. The framework's documentation confirms the behavior: "Inactive tabs will be moved Offstage and their animations disabled" (flutter/flutter, n.d.-b), and each CupertinoTabView has its own Navigator. The runnable copy's tests push a route inside the first tab, switch tabs and back, and find the route still there; with BottomNavigationBar, the previous tab's widget is gone.Using packages to build cross-platform UIs
Using a LayoutBuilder will only get you part of the way to a truly cross-platform UI. Certainly, you can use it to build a responsive layout, but what about a layout that will adjust its widgets to match whether you are on iOS or Android?
Cupertino widgets probably should not be in an Android application. Just the same, Material widgets would feel out of place on an iOS application.Would it not be nice if the application would adjust automatically, to match the platform it is on?
flutter_platform_widgets
Fortunately, a package exists which will do just this: flutter_platform_widgets. This package will use the information from Theme.of(context).platform to build different widgets depending on whether it finds TargetPlatform.android or TargetPlatform.ios. However, this behavior can be overridden for any supported platform (Android, iOS, Web, macOS, Fuchsia, Windows, and Linux).
flutter_platform_widgets will only provide builders for the different platforms; what you actually do with those builders is entirely up to you: you need not use Cupertino or Material at all.Let us look at some code:
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const PlatformApp(
home: MyStatelessWidget(),
);
}
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: PlatformWidget(
cupertino: (_, __) => Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(CupertinoIcons.flag),
Text('Using Cupertino widgets'),
],
),
material: (_, __) => Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(Icons.flag),
Text('Using Material widgets'),
],
),
),
),
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch10/lib/platform_widgets/detected.dart
In this example, if the platform is detected as iOS (or macOS), a CupertinoIcons flag will be displayed (along with a message telling you that we are using Cupertino widgets.) Likewise, if Android is detected, a Material Icons flag will be displayed.
Theme.of(context).platform. When no platform has been set, it checks kIsWeb first and uses the Web style, which is Material by default, so a browser on an iPhone also gets the Material widgets. On other platforms it reads Theme.of(context).platform: iOS and macOS default to Cupertino, while Android, Fuchsia, Windows and Linux default to Material (flutter_platform_widgets 8.0.0, lib/src/platform.dart; stryder-dev, n.d.). The PlatformStyleData override below changes the Web default.Forcing a platform style
What happens if you are testing on an Android device (or writing your code on a non-Apple computer, and simply do not have access to an iOS simulator?) We can set a style with an option, although note that this is not a replacement for testing on the actual platform:
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return PlatformProvider(
initialPlatform: TargetPlatform.iOS,
builder: (context) => const PlatformApp(
home: MyStatelessWidget(),
),
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch10/lib/platform_widgets/force_ios.dart
The PlatformProvider widget will also let us override styles for different platforms. For example, we could tell the application that when running on the Web, it should also use the Cupertino style:
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return PlatformProvider(
settings: PlatformSettingsData(
platformStyle: const PlatformStyleData(
web: PlatformStyle.Cupertino,
),
),
builder: (context) => const PlatformApp(
home: MyStatelessWidget(),
),
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch10/lib/platform_widgets/web_cupertino.dart
flutter_platform_widgets which take some of the legwork out of building a multi-platform UI. By leveraging some of the built-in platform widgets provided by the package, you can reduce the amount of code needed to write and maintain a feature. The less code you have, the less that can go wrong.Conclusion
Not every application needs to have a different look and feel, depending on the platform it runs on. However, many will require adjustments, sometimes slight and sometimes more extreme. Being able to dynamically adjust for a variety of screen sizes, orientations, and native platforms takes just a little bit of extra work but generally tends to pay off in the end.
In the upcoming chapter, we are going to talk about what to do when things go wrong. We will look at the tools and techniques we have available to us when we need to debug, troubleshoot, and figure out why there might be performance problems, such as a laggy UI, frame drops when scrolling, jitter, and so on.
Questions
- What is a responsive layout?
- Which widget can we use to build a responsive layout?
- When building a responsive layout, what considerations should you take when choosing how to build your screen-size-dependent widgets? What are some actions you can take to ensure you do not forget about accidentally removing important functionality?
- What is
dart:ioused for? - What platform(s) can
dart:ionot be used on? - How do you update your application's icon?
- Where can you find resources for designing a splash screen?
- What packages can be used to help ensure you have properly updated your app icon and splash screen?
- What are some packages that can be used to match the look and feel of a desktop operating system, such as Windows or Linux?
- What are the key differences between Android and iOS in terms of navigation principles?
- What is stacked navigation?
- What inherited widget contains information about the currently targeted platform?
- What package allows you to easily build platform-adaptive layouts?
Further reading
dart:io has its own page at https://dart.dev/libraries/dart-io (Dart, n.d.).References
- Dart. (n.d.). dart:io. Retrieved from Dart: https://dart.dev/libraries/dart-io (added, not in the book)
- Flutter. (n.d.). Read and write files. Retrieved from Flutter: https://docs.flutter.dev/cookbook/persistence/reading-writing-files (added, not in the book)
- flutter/flutter. (n.d.-a). async.dart (Flutter 3.29.0 source). Retrieved from GitHub: https://github.com/flutter/flutter/blob/3.29.0/packages/flutter/lib/src/widgets/async.dart (added, not in the book)
- flutter/flutter. (n.d.-b). tab_scaffold.dart (Flutter 3.29.0 source). Retrieved from GitHub: https://github.com/flutter/flutter/blob/3.29.0/packages/flutter/lib/src/cupertino/tab_scaffold.dart (added, not in the book)
- Internet Archive. (2026, May 19). AppStream/Icons (archived copy of the Ubuntu wiki page). Retrieved from the Wayback Machine: https://web.archive.org/web/20260519084602/https://wiki.ubuntu.com/AppStream/Icons (added, not in the book)
- stryder-dev. (n.d.). flutter_platform_widgets 8.0.0. Retrieved from pub.dev: https://pub.dev/packages/flutter_platform_widgets/versions/8.0.0 (added, not in the book)
State Management and the BLoC
Ephemeral versus app state, and one shopping cart built four ways — with an inherited widget, Provider, Cubit and BLoC.
Debugging, Troubleshooting, and Performance Considerations
Logging, breakpoints and exceptions, Flutter DevTools, jank and profile mode, ListView vs Column, and how to keep widget rebuilds cheap.