Flutter iOS模拟器Platform.operatingSystemVersion返回异常咨询
问题成因
该异常是Flutter 2.0.0稳定版的已知缺陷:
- 当应用以Debug模式运行在iOS模拟器上时,
dart:io库提供的Platform.operatingSystemVersion接口的取值逻辑异常,错误读取开发主机的macOS版本参数,没有读取模拟器沙箱内对应的iOS系统版本 - 从提供的日志可以直接验证匹配关系:接口返回的11.2.2和Flutter运行环境的macOS 11.2.2版本完全一致,和预期的iOS 14.4取值不匹配
- 该缺陷在Flutter 2.2及以上稳定版本中已被官方修复,在2.0.0版本环境下,不依赖第三方插件即可实现正确的系统版本获取。
无第三方依赖的实现方案
可直接通过Flutter内置的平台通道能力绕开该缺陷,全程不需要引入存在平台兼容问题的device_info插件:
Dart侧逻辑实现
仅引用SDK内置模块封装统一的版本获取方法,对非iOS平台、非异常场景仍沿用原有Platform接口的取值逻辑:
// 所有引用均为Flutter SDK内置库,无外部依赖 import 'dart:io'; import 'package:flutter/services.dart'; Future<String> getDeviceOSVersion() async { // Android、Web、桌面平台直接使用原有接口取值 if (!Platform.isIOS) { return Platform.operatingSystemVersion; } // iOS平台走原生通道取值,绕开内置Platform接口的bug const osInfoChannel = MethodChannel('app/os_info'); final version = await osInfoChannel.invokeMethod<String>('fetchOSVersion'); return version ?? 'unknown_version'; }
iOS原生侧适配
在iOS工程的启动入口注册和Dart侧约定同名的通道,收到取值请求时调用系统原生接口返回正确版本:
// iOS工程 AppDelegate.swift 内的注册逻辑 import UIKit import Flutter @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // 初始化和Dart侧同名的通道 let rootController = window?.rootViewController as! FlutterViewController let infoChannel = FlutterMethodChannel( name: "app/os_info", binaryMessenger: rootController!.binaryMessenger ) infoChannel.setMethodCallHandler { call, result in if call.method == "fetchOSVersion" { // 直接读取当前运行环境的系统版本,模拟器/真机取值均准确,不会读取宿主主机参数 result(UIDevice.current.systemVersion) } else { result(FlutterError(code: "method_not_implemented", message: nil, details: nil)) } } GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
实现注意事项
- 整套实现完全基于Flutter SDK内置能力,没有引入任何第三方插件,自然不存在第三方插件对macOS平台支持不全的兼容问题
- 该缺陷仅在Debug调试模式下的iOS模拟器场景触发,Release模式下的模拟器、真机环境中,原
Platform.operatingSystemVersion接口取值正常,不需要额外改造 - 后续如果升级Flutter版本到2.2以上,该缺陷会被官方修复,可直接移除自定义的平台通道逻辑,回归使用内置
Platform接口的取值能力
内容的提问来源于stack exchange,提问作者Larry Aasen
相关产品推荐
相关产品推荐

