How to check platform at runtime
Asked Answered
I

3

7

How could I check the platform (Android/iOS) at runtime?

I’d like to differ my flutter application behaviour if I'm on Android rather than I'm on iOS.

Like this:

_openMap() async {
    // Android
    var url = 'geo:52.32,4.917';
    if (/* i'm on iOS */) {
      url = 'http://maps.apple.com/?ll=52.32,4.917';
    }
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
Initiation answered 18/3, 2018 at 12:11 Comment(0)
I
15

I've search a bit on SO and tryed also to Google it but this scenario is not so well indexed and so I think my question and anser could help starting developing on Flutter.

If you have to check the OS or the Platform of your device at runtime you could use the Platform class of dart.io library.

import 'dart:io'

This way you could check in a way like that:

_openMap() async {
    // Android
    var url = 'geo:52.32,4.917';
    if (Platform.isIOS) {
      // iOS
      url = 'http://maps.apple.com/?ll=52.32,4.917';
    } else if (Platform.isWindows) {
      // TODO - something to do?
    }
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

Instead if you also need some deep insight of the device you could use the dart device_info package.

There's a good example here.

This way you could also check not only the platform you are running on but also the specific version of OS (iOS 9, 10.3, 11.x, Lollipop, Jellybean, etc.) and many others device info.

UPDATE:

After Flutter Live 2018 --> Look at this gr8 youtube video for Platform Aware Widget and the best way to be compliant with Android and iOS UI from the same codebase.

Initiation answered 18/3, 2018 at 12:11 Comment(0)
C
12

The recommended way to get the current platform is by using Theme.

Theme.of(context).platform

This way, you could potentially override that value with a custom Theme at runtime and see immediately all the changes.

Cockrell answered 18/3, 2018 at 13:25 Comment(2)
Oh, good to know! Thank you! It works, I've tested, and for a simple check it requires a bit more coding, but If you need runtime platform changing could be useful. This will improve my question for sure! Thank you +1!Initiation
Anyway, remember that in flutter everything is a widget and that's not a joke. Platform check should be done with widgets too :pDisplease
M
3
import 'dart:io'

String os = Platform.operatingSystem;

This is simple way to check platform and also allows a lot of other useful information about the device being used. Link to docs about the Platform class.

Mitosis answered 7/9, 2020 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.