platform_detect 是一个轻量级的 Flutter Web 库,旨在运行时识别当前的操作系统和浏览器环境。它提供了简单可靠的平台信息检测功能,例如操作系统(如 Windows、macOS、Linux)和浏览器(如 Chrome、Safari、Firefox),使开发者能够根据用户的环境定制行为或 UI。该包专为 Web 应用优化,并与 Flutter 的 Web 平台无缝集成。它依赖于客户端 JavaScript 检测,无需外部依赖。
适合场景
为不同浏览器适配UI布局
根据操作系统有条件地启用功能
调试平台特定问题
按浏览器优化性能
处理浏览器兼容性差异
主要特点
轻量且快速
无外部依赖
支持主流浏览器和操作系统
简单 API,结果清晰
专为 Flutter Web 打造
适合对象
仅限网络的Flutter应用
跨浏览器兼容性逻辑
环境感知的UI渲染
开发者工具和诊断
使用建议
仅限网页平台
依赖浏览器/用户代理字符串
可能需要针对新浏览器版本进行更新
不适用于移动或桌面应用程序
原始 README
以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。
platform_detect
A library for detecting browser and platform type and version.
Usage
A simple usage example:
import'package:platform_detect/platform_detect.dart';
main() {
if (browser.isChrome) {
print('thank you for being a friend');
}
if (operatingSystem.isMac) {
print('');
}
}
Decorating the <html> element with CSS classes
This library can also be used to place CSS classes on the <html> element based on the
operating system, browser, or a specific supported feature.
Add the decorator.dart import as shown in the example below, and call decorateRootNodeWithPlatformClasses
within main in your application.
By default, the only browser feature that the library detects for you is touch / mstouch.
You can extend this functionality to bake in a Modernizr-esque implementation by creating your
own Feature instances, and passing a list of them as the features argument to
decorateRootNodeWithPlatformClasses:
import'package:platform_detect/platform_detect.dart';
import'package:platform_detect/decorator.dart';
// For instance, if you need to detect whether a browser supports H5 canvas stuff...var canvasFeature = newFeature('canvas', newCanvasElement().context2D != null);
main() {
// Decorate HTML elementdecorateRootNodeWithPlatformClasses(features: [canvasFeature]);
// Or use the `isSupported` field somewhere else in your app...if (canvasFeature.isSupported) {
// Do something
} else {
// Fall back / warn / etc...
}
}
The <html> node of your application will now look like something like this
for browsers that support canvas: