Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check platform at runtime

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';
    }
  }
like image 684
shadowsheep Avatar asked Mar 18 '18 12:03

shadowsheep


3 Answers

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.

like image 175
shadowsheep Avatar answered Nov 20 '22 20:11

shadowsheep


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.

like image 12
Rémi Rousselet Avatar answered Nov 20 '22 20:11

Rémi Rousselet


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.

like image 3
Michael DiCioccio Avatar answered Nov 20 '22 20:11

Michael DiCioccio