Sometimes, you need to know what operating system your flutter app is running on, most times for theming purposes, but sometimes for functionalities !
There are basically 2 popular ways to do this (3 popular methods if you are willing to use a package specifically to simplify theme issues !), let us assume we will be calling a certain method called _iosMethod if we are on iOS, and a _genericMethod if we are on any other platform
The most common use case is to determine whether to use Material or Cupertino, to give the application that native look the users are used to… in any case… here are the two methods
In both methods, we have a function called doStuff
Method 1
In the first method, we get the platform using the Theme (We must pass context to function) !
The ThemeData object has an enum called TargetPlatform… we will use that here
void doStuff(BuildContext context) {
final platform = Theme.of(context).platform;
if (platform == TargetPlatform.iOS) {
_iosMethod(context);
} else {
_genericMethod(context);
}
}
The possible options that can come out of this enum are (android, iOS, linux, macOS, windows, fuchsia)
Method 2
Here, we can simply start by importing (import ‘dart:io’ show Platform;), then use it directly
import 'dart:io' show Platform;
...
...
void doStuff(BuildContext context) {
if (Platform.isIOS) {
_iosMethod(context);
} else {
_genericMethod(context);
}
}
Method 3
This time, we will be using the package (flutter_platform_widgets), this package is very useful for theming your application to have the look and feel of the default theme of the OS…
things become very simple with this package, all you need is the line
return PlatformElevatedButton(onPressed: onPressed, child: child);