How to detect the host platform from Dart code?

· 3 min read
Detect Host Platform From Dart Code
Detect Host Platform From Dart Code

As we all are aware that Flutter is a cross-platform development for natively compiled applications for mobile, web, and desktop from a single codebase. so UI that should differ slightly on iOS and Android, i.e. on different platforms, there must be a way to detect which one the app is running on.

How to detect the host platform from Dart code?

To detect the host platform from dart code users need to import a package like below:

import 'dart:io' show Platform;

Now user can identify the host platform using the code snippet as below:

if (Platform.isAndroid) {
  // Android-specific code
} else if (Platform.isIOS) {
  // iOS-specific code
}

Users can also detect if you are running on the web using kIsWeb, a global constant indicating if the application was compiled to run on the web.

import 'package:flutter/foundation.dart' show kIsWeb;
if (kIsWeb) {
  // running on the web!
} else {
  // NOT running on the web! You can check for additional platforms here.
}

Users can also import the platform package like below:

import 'dart:io' show Platform;

Now users need to identify Operating System using the code snippet as below:

String os = Platform.operatingSystem; //in your code
print(os);

It is simple just to import the io library.

import'dart:io' show Platform;
void main(){
if(Platform.isIOS){
  return someThing();
}else if(Platform.isAndroid){
  return otherThing();
}else if(Platform.isMacOS){
  return anotherThing();
}

or in a very simple way.

Platform.isIOS ? someThing() : anOther(),

You can use the Universal Platform package

import 'package:universal_platform/universal_platform.dart';
bool isIos = UniversalPlatform.isIOS;
bool isAndroid = UniversalPlatform.isAndroid;
bool isWeb = UniversalPlatform.isWeb;
print('iOS: $isIos');
print('Android: $isAndroid');
print('Web: $isWeb');

Conclusion:

In this article, we have learned How to detect the host platform from Dart code?

Thanks for being with us on a Flutter Journey!!!
Keep Fluttering.

Do let us know if you need any assistance with Flutter Development?

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply