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