How to check platform at runtime

我只是一个虾纸丫 提交于 2019-12-12 11:28:11

问题


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';
    }
  }

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/49347721/how-to-check-platform-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!