How do you detect the host platform from Dart code

2020-02-08 02:52发布

问题:

For UI that should differ slightly on iOS and Android, there must be a way to detect which one you're running on, but I couldn't find it in the docs. What is it?

回答1:

import 'dart:io' show Platform;

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

Other options include:

Platform.isFuchsia
Platform.isLinux
Platform.isMacOS
Platform.isWindows
kIsWeb // A global constant indicating if the application was compiled to run on the web
  • Platform documentation: https://docs.flutter.io/flutter/dart-io/Platform-class.html
  • kIsWeb documentation: https://api.flutter.dev/flutter/foundation/kIsWeb-constant.html


回答2:

Thanks to Collin, the final answer is:

bool isIOS = Theme.of(context).platform == TargetPlatform.iOS;


回答3:

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.



回答4:

import 'dart:io' show Platform;  //at the top

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


回答5:

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


回答6:

You can do

defaultTargetPlatform == TargetPlatform.iOS
          ? kIOSTheme
          : kDefaultTheme,

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



标签: dart flutter