Flutter Web端如何检测浏览器运行所在的设备类型
Flutter Web端识别运行设备类型方案
Flutter Web运行在浏览器沙箱环境中,dart:io 库下的 Platform 类本身不支持Web上下文,直接调用会抛出运行时异常;kIsWeb 仅用于判断当前编译目标是否为Web,自然无法区分具体运行的设备类型,所有设备判断逻辑都需要基于浏览器暴露的API实现。
方案1:无第三方依赖原生实现
核心逻辑是读取浏览器navigator对象的User Agent字符串做特征匹配,不需要引入额外依赖:
- 先通过
kIsWeb做环境兜底,避免非Web环境导入Web专属API导致编译报错 - 导入
dart:html获取浏览器window对象 - 读取UA字符串做关键字匹配,补充触屏点判断解决iPadOS默认请求桌面站点导致的识别错误
import 'package:flutter/foundation.dart'; import 'dart:html' as html; // 自定义设备类型枚举 enum DeviceType { android, ios, windows, macos, linux, unknown } DeviceType getCurrentDeviceType() { // 非Web环境直接返回未知 if (!kIsWeb) return DeviceType.unknown; final userAgent = html.window.navigator.userAgent.toLowerCase(); final maxTouchPoints = html.window.navigator.maxTouchPoints; if (userAgent.contains('android')) { return DeviceType.android; } // 兼容旧版iOS和iPadOS桌面模式 if (userAgent.contains('iphone') || userAgent.contains('ipad') || userAgent.contains('ipod') || (userAgent.contains('macintosh') && maxTouchPoints > 0)) { return DeviceType.ios; } if (userAgent.contains('windows')) { return DeviceType.windows; } if (userAgent.contains('macintosh') || userAgent.contains('mac os')) { return DeviceType.macos; } if (userAgent.contains('linux')) { return DeviceType.linux; } return DeviceType.unknown; }
方案2:使用成熟社区包简化逻辑
如果不想自己维护UA匹配规则,可以直接用社区广泛使用的device_info_plus包,这个包已经封装了多端包括Web端的设备信息读取逻辑:
- 第一步:在
pubspec.yaml中添加device_info_plus依赖,选用pub上的最新稳定版本即可 - 第二步:调用包封装的API读取Web端设备信息,示例代码如下:
import 'package:flutter/foundation.dart'; import 'package:device_info_plus/device_info_plus.dart'; import 'dart:html' as html; enum DeviceType { android, ios, windows, macos, linux, unknown } Future<DeviceType> getCurrentDeviceType() async { if (!kIsWeb) return DeviceType.unknown; final deviceInfoPlugin = DeviceInfoPlugin(); final webInfo = await deviceInfoPlugin.webBrowserInfo; final maxTouchPoints = html.window.navigator.maxTouchPoints; switch (webInfo.platform?.toLowerCase()) { case 'android': return DeviceType.android; case 'iphone': case 'ipad': case 'ipod': return DeviceType.ios; case 'win32': return DeviceType.windows; case 'macintel': // 兼容iPad桌面模式 return maxTouchPoints > 0 ? DeviceType.ios : DeviceType.macos; case 'linux x86_64': return DeviceType.linux; default: return DeviceType.unknown; } }
注意事项
所有Web专属API(包括dart:html的相关调用、Web端专属的插件方法)必须包裹在kIsWeb判断逻辑内,否则在原生端编译时会因为找不到对应API抛出编译错误
内容的提问来源于stack exchange,提问作者user3808307
相关产品推荐
相关产品推荐

