How do you detect the host platform from Dart code?
Asked Answered
A

23

481

For 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, but I couldn't find it in the docs. What is it?

Arsenault answered 28/8, 2017 at 17:31 Comment(0)
D
943
import 'dart:io' show Platform;

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

All options include:

Platform.isAndroid
Platform.isFuchsia
Platform.isIOS
Platform.isLinux
Platform.isMacOS
Platform.isWindows

You 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.
}
Democrat answered 7/6, 2018 at 15:2 Comment(5)
Undefined name 'Platform'.dart(undefined_identifier) Is there any per-requisites to use Platform?Throaty
I have updated my answer to include the needed import.Democrat
@NatoBoram you have to call Platform.isAndroid in a method of class, direct call in class didnt workGracye
Note that this won't work for flutter web. Throws an exception because of dependence on dart:ioScriven
@Scriven if you check kIsWeb before checking other platforms, like my answer shows, it will work just fine. I just verified this on Dartpad web.Democrat
A
134

Thanks to Collin, the final answer is:

bool isIOS = Theme.of(context).platform == TargetPlatform.iOS;
Arsenault answered 28/8, 2017 at 21:6 Comment(3)
Only this answer is up-to-date with the latest Flutter framework. The rest answers are not wrong but defaultTargetPlatform seems to be no longer part of the frameworkSuperbomb
This solution allow you to change the platform during tests, something that I couldn't with Platform.isIOSGaleiform
Watch out on this solution. If it's called in initstate() it will throw an exception as Theme.of() is a inherited widgets and will listen to changes. Which cannot be done in initstate() so it throws exceptionFullmer
S
47

Although defaultTargetPlatform will work, I would suggest using Theme.of(context).targetPlatform. This enables testing of iOS behavior (because defaultTargetPlatform is always TargetPlatform.android in tests). It also allows ancestors of your widget to override its target platform by wrapping it in a Theme widget.

Stain answered 28/8, 2017 at 17:58 Comment(4)
May I ask what is the difference between what is proposed and this if (Platform.isIOS) {//my iOS widgets}Sheugh
Platform.isIOS has the same problems as defaultTargetPlatform. It doesn't work in tests and can't be overwritten by the Theme widget.Stain
Now you can override defaultTargetPlatform in unittest with debugDefaultTargetPlatformOverride api.flutter.dev/flutter/foundation/…Flagman
Yuwen Yan is wrong, per debugDefaultTargetPlatform doc Setting debugDefaultTargetPlatformOverride (as opposed to, say, ThemeData.platform) will cause unexpected and undesirable effects. For example, setting this to TargetPlatform.iOS when the application is running on Android will cause the TalkBack accessibility tool on Android to be confused because it would be receiving data intended for iOS VoiceOver. Similarly, setting it to TargetPlatform.android while on iOS will cause certainly widgets to work assuming the presence of a system-wide back button, whichFlame
W
42
import 'dart:io' show Platform;  //at the top

String os = Platform.operatingSystem; //in your code
print(os);
Whorehouse answered 16/2, 2019 at 12:41 Comment(1)
Note that this won't work for flutter web. Throws an exception because of dependence on dart:ioScriven
S
26

It is simple just 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 very simple way

Platform.isIOS ? someThing() : anOther(),
Stylistic answered 25/7, 2020 at 19:57 Comment(1)
This is the correct answer. You simply need to remove any dart:HTML import from your code as it will cause an error.Brinn
I
25
if (Platform.isAndroid) {
  // Android-specific code/UI Component
} else if (Platform.isIOS) {
  // iOS-specific code/UI Component
}

Don't forget to import IO Library.

import 'dart:io';

If you are using import 'dart:html'; too in same file then you have to specify Platform definition as both libraries has definition of "Platform"

in that case use Platform Specific Code like Below:

import 'dart:io' as IO;
import 'dart:html';

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

If you are looking into Platform Integration properly I would Suggest Use Complete Example on Flutter site: https://flutter.dev/docs/development/platform-integration/platform-channels

Itemize answered 9/2, 2021 at 4:45 Comment(0)
G
23

for more simple way for web and app both.try this

import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;


var platformName = '';
if (kIsWeb) {
  platformName = "Web";
} else {
  if (Platform.isAndroid) {
    platformName = "Android";
  } else if (Platform.isIOS) {
    platformName = "IOS";
  } else if (Platform.isFuchsia) {
    platformName = "Fuchsia";
  } else if (Platform.isLinux) {
    platformName = "Linux";
  } else if (Platform.isMacOS) {
    platformName = "MacOS";
  } else if (Platform.isWindows) {
    platformName = "Windows";
  }
}
print("platformName :- "+platformName.toString());
Goldiegoldilocks answered 18/11, 2020 at 7:6 Comment(0)
C
18

You can do

defaultTargetPlatform == TargetPlatform.iOS
          ? kIOSTheme
          : kDefaultTheme,

from import 'package:flutter/foundation.dart';

Citarella answered 28/8, 2017 at 17:38 Comment(2)
It doesn't work anymore. I failed to get defaultTargetPlatform.Urbane
May be with the import that you added yesterday to the post. :DUrbane
F
15

Most "Flutter" answer is as follows:

import 'package:flutter/foundation.dart' show TargetPlatform;

//...

if(Theme.of(context).platform == TargetPlatform.android)
    //do sth for Android
else if(Theme.of(context).platform == TargetPlatform.iOS)
    //do sth else for iOS
else if(Theme.of(context).platform == TargetPlatform.fuchsia)
    //even do sth else for Fuchsia OS
Fiddler answered 15/2, 2019 at 12:14 Comment(0)
A
10

you can add this extension file (platform_ext.dart) to the project and call in any object

import 'dart:io';
import 'package:flutter/foundation.dart' show kIsWeb;

extension Target on Object {
  bool isAndroid() {
    return Platform.isAndroid;
  } 
  bool isIOS() {
    return Platform.isIOS;
  } 
  bool isLinux() {
  return Platform.isLinux;
  } 
  bool isWindows() {
  return Platform.isWindows; 
  }
  bool isMacOS() {
  return Platform.isMacOS; 
  }
  bool isWeb() {
  return kIsWeb; 
  }
  // ···
}

just import the file and call it

   import 'platform_ext.dart';
        ....
        @override
          Widget build(BuildContext context) {
            return isAndroid()? Text("Android"):Text("Not Android");
          }
Anamorphic answered 27/8, 2021 at 13:5 Comment(1)
This is really an overkill. Why would each and every object knew about Platforms? While it is convenient it is terrible now that your String object will know what platform it is.. Keep this in separate class that you can instantiate when you need this info..Autograft
W
7

You can use Universal Platform package:

https://pub.dev/packages/universal_platform

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');
Wicked answered 9/5, 2020 at 18:50 Comment(2)
I recommend this... because only after I noticed strange behavior of Platform.isIOS on different browsers, I felt this was a package to go to! By the way it does deliver all 7 platformsEditor
universal_platform just uses Platform.isWindows, Platform.isAndroid, etc. under the hood.Turntable
E
7
import 'dart:io' as io;

if(io.Platform.isAndroid){
 doSomething();
}else {
 doSomethingElse();
}
Enteron answered 29/5, 2021 at 13:45 Comment(0)
P
6

So here is a little utility I use to detect platforms and os to be reactive as appropriate.

import'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;

class Util {

  os getPlatform() {
    if (kIsWeb) {
      return os.Web;
    } else if (Platform.isIOS) {
      return os.IOS;
    } else if (Platform.isAndroid) {
      return os.Android;
    } else if (Platform.isFuchsia) {
      return os.Fuchsia;
    } else if (Platform.isLinux) {
      return os.Linux;
    } else if (Platform.isMacOS) {
      return os.MacOS;
    } else if (Platform.isWindows) {
      return os.Windows;
    }
    return os.Unknown;
  }

  bool isWeb() {
    return (getPlatform()==os.Web);
  }

  bool isMobile() {
    os platform = getPlatform();
    return (platform == os.Android || platform == os.IOS || platform== os.Fuchsia);
  }

  bool isComputer() {
    os platform = getPlatform();
    return (platform == os.Linux || platform == os.MacOS || platform== os.Windows);
  }

}

enum os { Unknown, Web, Android, Fuchsia, IOS, Linux, MacOS, Windows }

Portuguese answered 30/7, 2021 at 18:13 Comment(0)
P
5
import 'dart:io' show Platform;

if (Platform.isAndroid) {
  // Android-specific code
} else if (Platform.isIOS) {
  // iOS-specific code
}else if (Platform.isFuchsia) {
  // Fuchsia-specific code
}else if (Platform.isLinux) {
  // Linux-specific code
}else if (Platform.isMacOS) {
  // MacOS-specific code
}else if (Platform.isWindows) {
  // Windows-specific code
}else if (Platform.isWindows) {
  // Windows-specific code
}

for 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.
}
Preventive answered 20/4, 2022 at 13:19 Comment(0)
F
5

If you import both "dart:io" and "dart:html", it does not understand which Platform to import and gives error. So import one of them.

import 'dart:io';
Platform.isIOS ? CupertinoWidget() : MaterialWidget()
Footie answered 20/12, 2022 at 16:54 Comment(0)
O
3

EDITED

Since I have published the flutter_helper_utils package, and added all the boilerplate code in it. You can easily:

import 'package:flutter_helper_utils/flutter_helper_utils.dart';

context.isMobile;
context.isApple;
context.isIOS;
context.isMobileWeb;
context.isAndroidWeb;
// etc...

The package also provides a lot of helper functions and extensions.


Previous Answer:

You can add this extension to your project

import 'package:flutter/material.dart';

extension PlatformExtension on BuildContext {
  bool get isMobile =>
      Theme.of(this).platform == TargetPlatform.iOS ||
      Theme.of(this).platform == TargetPlatform.android;

  bool get isDesktop =>
      Theme.of(this).platform == TargetPlatform.macOS ||
      Theme.of(this).platform == TargetPlatform.windows ||
      Theme.of(this).platform == TargetPlatform.linux;
}

extension TargetPlatformExtension on TargetPlatform {
  bool get isMobile =>
      this == TargetPlatform.iOS || this == TargetPlatform.android;

  bool get isDesktop =>
      this == TargetPlatform.linux ||
      this == TargetPlatform.macOS ||
      this == TargetPlatform.windows;
}

Now you can access the host platform using.

  1. BuildContext => context.isDesktop

  2. TargetPlatform => defaultTargetPlatform.isDesktop

It is recommended to access the platform from context.

To detect if your app is running on browsers, you can use the kIsWeb constant from the foundation library.

import 'package:flutter/foundation.dart';

  log('$kIsWeb'); // will print true if the app is running on a browser

Note that if you are running a web app on a desktop, the isDesktop getter will return true, and same thing for mobile platforms. And to avoid that.

import 'package:flutter/foundation.dart';

  if (!kIsWeb && defaultTargetPlatform.isDesktop) {
    // do stuff for desktop apps only
  }

  if (!kIsWeb && defaultTargetPlatform.isMobile) {
    // do stuff for mobile apps only
  }

You can modify the extensions to get your preferred implementation.

Oraorabel answered 14/11, 2022 at 15:20 Comment(0)
M
3
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;

class PlatformUtil {
  static const bool isWeb = kIsWeb;

  static bool get isMobile {
    if (kIsWeb) {
      return false;
    } else {
      return Platform.isIOS || Platform.isAndroid;
    }
  }

  static bool get isDesktop {
    if (kIsWeb) {
      return false;
    } else {
      return Platform.isLinux || Platform.isFuchsia || Platform.isWindows || Platform.isMacOS;
    }
  }
}
Medick answered 24/11, 2023 at 3:51 Comment(0)
B
2
**multiple platform you check and run your code according specific platform **

bool isIOS = Theme.of(context).platform == TargetPlatform.iOS;
bool isAndroid = Theme.of(context).platform == TargetPlatform.android;
bool islinux = Theme.of(context).platform == TargetPlatform.linux;
bool isfuchsia = Theme.of(context).platform == TargetPlatform.fuchsia;
bool isMacOS = Theme.of(context).platform == TargetPlatform.macOS;
bool iswindows = Theme.of(context).platform == TargetPlatform.windows;
Bor answered 10/8, 2022 at 12:49 Comment(0)
D
1

If you just need a string for logging purposes, you can use Platform.operatingSystem, which returns the OS name as a lowercase string.

import 'dart:io';
import 'package:flutter/foundation.dart';

String _getPlatform() {
  if (kIsWeb) return 'web';
  return Platform.operatingSystem;
}
Daffie answered 17/8, 2021 at 4:10 Comment(1)
Until you try to use that during widget and goldens testing where we wrap the widget with MaterialApp and set the platform simulated through ThemeData platform property. Then it fails quite big!Flame
F
0

Checking Host Platform in Dart.

import 'dart:io' as IO;

_checkingHostPlatform(){
    if(IO.Platform.isAndroid){
      //Execute code for android
    }else if(IO.Platform.isIOS){
      //Execute code for iOS
    }else{
      //Execute code for other platforms
    }
  }
Fat answered 21/1, 2022 at 9:20 Comment(0)
L
0

This custom-created class will help you to detect the platform:

import 'package:flutter/foundation.dart'
    show defaultTargetPlatform, kIsWeb, TargetPlatform;

enum Os {
  web,
  android,
  ios,
  macOS,
  linux,
  windows,
  fuchsia,
}

class Platform {
  const Platform();

  /// Platform is Web.
  static bool get isWeb => os == Os.web;

  /// Platform is Android.
  static bool get isAndroid => os == Os.android;

  /// Platform is IOS.
  static bool get isIOS => os == Os.ios;

  /// Platform is Fuchsia.
  static bool get isFuchsia => os == Os.fuchsia;

  /// Platform is Linux.
  static bool get isLinux => os == Os.linux;

  /// Platform is MacOS.
  static bool get isMacOS => os == Os.macOS;

  /// Platform is Windows.
  static bool get isWindows => os == Os.windows;

  /// Platform is Android or IOS.
  static bool get isMobile => isAndroid || isIOS;

  /// Platform is Android or IOS or Fuchsia.
  static bool get isFullMobile => isMobile || isFuchsia;

  /// Platform is Linux or Windows or MacOS.
  static bool get isDesktop => isLinux || isWindows || isMacOS;

  /// Getting the os name.
  static Os get os {
    if (kIsWeb) {
      return Os.web;
    }
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
        return Os.android;
      case TargetPlatform.iOS:
        return Os.ios;
      case TargetPlatform.macOS:
        return Os.macOS;
      case TargetPlatform.windows:
        return Os.windows;
      case TargetPlatform.fuchsia:
        return Os.fuchsia;
      case TargetPlatform.linux:
        return Os.linux;
    }
  }
}

Loraine answered 29/1, 2023 at 10:59 Comment(1)
This is problematic, because web isn't entirely a seperate platform. Users can be on Android mobile and look at the site from their browsers, for example.Affright
F
0

Note most of the answers here are wrong due to:

  1. defaultTargetPlatform is always set to android in unit testing and setting to something else always causes problems per the Flutter Docs explainations.

  2. We always wrap widgets to golden, BDD, and widget test with a MaterialApp in which we set the ThemeData.platform property to simulate the target platfrom.

Thus the solution should be this:

import 'package:flutter/material.dart';

extension PlatformExtension on BuildContext {
  bool get isMobile =>
      Theme.of(this).platform == TargetPlatform.iOS ||
      Theme.of(this).platform == TargetPlatform.android ||
      Theme.of(this).platform == TargetPlatform.fuchsia;

  bool get isDesktop =>
      Theme.of(this).platform == TargetPlatform.macOS ||
      Theme.of(this).platform == TargetPlatform.windows ||
      Theme.of(this).platform == TargetPlatform.linux;
  
  bool get isIOS => Theme.of(this).platform == TargetPlatform.iOS;
  bool get isAndroid => Theme.of(this).platform == TargetPlatform.android;
  bool get isFuchsia => Theme.of(this).platform == TargetPlatform.fuchsia;
  bool get isLinux => Theme.of(this).platform == TargetPlatform.linux;
  bool get isWindows => Theme.of(this).platform == TargetPlatform.windows;
  bool get isMacOS => Theme.of(this).platform == TargetPlatform.macOS;
  
}

There is a growing list of Flutter Mentors on substack that do one day a week chats to answer questions such as this and that list is on the right side of my substack and my substack link is in my profile.

Flame answered 14/11, 2023 at 15:3 Comment(0)
H
-2

Below two line will give you the name of OS.

import 'dart:io' as OS; //on top

OS.Platform.operatingSystem // use this to get name of OS

If you want checks based on OS use below properties:

  1. OS.Platform.isAndroid
  2. OS.Platform.isIOS
Helgahelge answered 11/3 at 7:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.