universal_html 提供了一个统一的 'dart:html' API,可在所有平台上运行,包括移动设备、桌面和服务器端环境上的 Flutter。它无论在何种运行时环境下都能实现一致的 HTML 和 XML 处理,简化了跨平台开发。该包通过提供兼容的 DOM 操作、HTTP 请求以及结构化内容解析接口,弥合了 Web 与非 Web 环境之间的差距。非常适合在 Web 和后端服务之间共享逻辑,减少代码重复并优化开发流程。
适合场景
跨平台的 Web 和服务器逻辑
共享 HTML/XML 解析
服务器端渲染工具
Flutter 应用中的 Web 组件复用
构建通用 Dart 应用程序
主要特点
跨平台的 dart:html API
支持在所有平台上进行 DOM 操作
内置的 XML/HTML 解析
与 Flutter 和服务器无缝配合
轻量且依赖极少
适合对象
面向多平台的开发者
需要HTML处理的后端服务
需要类似 Web 功能的 Flutter 应用
Web 和服务器之间的代码共享
避免使用平台特定条件判断的项目
使用建议
非 Web 平台上的浏览器特定功能有限
不支持网页以外的某些 DOM 事件
服务器端执行时性能可能有所不同
不用于完整的浏览器模拟
需要谨慎处理异步操作
原始 README
以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。
Introduction
A cross-platform replacement for dart:html (or package:web):
Eases cross-platform development
You can use this package in browsers, mobile, desktop, and server-side VM, and Node.JS.
Just replace dart:html / package:web imports with package:universal_html/universal_html.dart. Normal
dart:html will continue to be used when application run in browsers.
Extensive support for processing HTML and XML documents
The project is licensed under the Apache License 2.0. Some of the source code was adopted
from the original dart:html in Dart SDK,
which is documented in the relevant files.
EventSource requests from real browsers are typically authenticated using cookies.
If you want to add cookies or customize other HTTP headers, you need to use
EventSourceOutsideBrowser:
import'package:universal_html/universal_html.dart';
import'dart:io'showCookie;
Future<void> main() async {
final eventSource = EventSource('http://example.com/events');
// The following block will NOT be executed in browsers.// Because compiler can infer instances of EventSourceOutsideBrowser are never constructed,// it will not appear in Javascript either.if (eventSource isEventSourceOutsideBrowser) {
eventSource.onHttpClientRequest = (eventSource, request) {
request.headers.set('Authorization', 'example');
request.cookies.add(Cookie('name', 'value'));
};
eventSource.onHttpClientResponse = (eventSource, request, response) {
// ...
};
}
awaitfor (var message in eventSource.onMessage) {
print('Event:');
print(' type: ${message.type}');
print(' data: ${message.data}');
}
}