[dart] Dart 코드에서 호스트 플랫폼을 어떻게 감지합니까?

iOSAndroid 에서 약간 다른 UI , 즉 다른 플랫폼 에서 앱이 실행되는 것을 감지하는 방법이 있어야하지만 문서에서 찾을 수 없습니다. 뭐야?



답변

import 'dart:io' show Platform;

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

모든 옵션은 다음과 같습니다.

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

kIsWeb응용 프로그램이 웹에서 실행되도록 컴파일되었는지 여부를 나타내는 전역 상수 인을 사용하여 웹에서 실행 중인지 감지 할 수도 있습니다 .

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.
}

답변

Collin 덕분에 최종 답변은 다음과 같습니다.

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


답변

defaultTargetPlatform작동 하지만 Theme.of(context).targetPlatform. 이를 통해 iOS 동작을 테스트 할 수 있습니다 ( defaultTargetPlatform항상 TargetPlatform.android테스트 중이므로 ). 또한 위젯의 조상이 위젯으로 래핑하여 대상 플랫폼을 재정의 할 수 있습니다 Theme.


답변

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

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


답변

대부분의 “Flutter”대답은 다음과 같습니다.

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


답변

넌 할 수있어

defaultTargetPlatform == TargetPlatform.iOS
          ? kIOSTheme
          : kDefaultTheme,

…에서 import 'package:flutter/foundation.dart';


답변

Universal Platform 패키지를 사용할 수 있습니다.

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