搜索插件、代码仓与 APP 分类

插件详情v2.3.0

universal_html

一个可在所有平台(包括 Flutter 和服务器端)上运行的 'dart:html',可简化跨平台开发和 HTML/XML 处理。

AndroidiOSmacOSWindowsLinux
近 30 天下载
66.2万
喜欢数
516
Pub 分数
150

安装插件

flutter pub add universal_html

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

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 原文快照,最新内容请访问源码仓库。

Pub Package package publisher Github Actions CI

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
  • EventSource streaming support
    • Cross-platform dart:html EventSource ("application/event-stream").
    • If you want to customize EventSource HTTP headers outside browsers, see EventSourceOutsideBrowser.

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.

Documentation

Similar projects

Getting started

1. Add dependency

In pubspec.yaml:

dependencies:
  universal_html: ^2.3.0

2. Use

import "package:universal_html/universal_html.dart";

void main() {
  // Create a DOM tree
  final div = DivElement();
  div.append(Element.tag("h1")
    ..classes.add("greeting")
    ..appendText("Hello world!"));

  // Print outer HTML
  print(div.outerHtml);
  // --> <div><h1>Hello world</h1></div>

  // Do a CSS query
  print(div.querySelector("div > .greeting").text);
  // --> Hello world
}

Examples

Parsing HTML

Use parseHtmlDocument:

import 'package:universal_html/parsing.dart';

void main() {
  final htmlDocument = parseHtmlDocument('<html>...</html>');
}

Parsing XML

Use parseXmlDocument:

import 'package:universal_html/parsing.dart';

void main() {
  final xmlDocument = parseXmlDocument('<xml>...</xml>');
}

Scraping a website

Load a Window with WindowController:

import 'dart:io' show Cookie;
import 'package:universal_html/controller.dart';

Future main() async {
  // Load a document.
  final controller = WindowController();
  controller.defaultHttpClient.userAgent = 'My Hacker News client';
  await controller.openHttp(
    method: 'GET',
    uri: Uri.parse("https://news.ycombinator.com/"),
    onRequest: (HttpClientRequest request) {
      // Add custom headers
      request.headers.set('Authorization', 'headerValue');
      request.cookies.add(Cookie('cookieName', 'cookieValue'));
    },
    onResponse: (HttpClientResponse response) {
      print('Status code: ${response.statusCode}');
    },
  );

  // Select the top story using a CSS query
  final titleElements = controller.document.querySelectorAll(".athing > .title");
  final topStoryTitle = titleElements.first.text;

  // Print result
  print("Top Hacker News story is: $topStoryTitle");
}

EventSource

EventSource (see mozilla.org) is a browser API for reading "application/event-stream" streams. It has been supported by browsers for a long time.

import 'package:universal_html/universal_html.dart';

Future<void> main() async {
  final eventSource = EventSource('http://example.com/events');
  await for (var message in event.onMessage) {
    print('Event type: ${message.type}');
    print('Event data: ${message.data}');
  }
}

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' show Cookie;

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 is EventSourceOutsideBrowser) {
    eventSource.onHttpClientRequest = (eventSource, request) {
      request.headers.set('Authorization', 'example');
      request.cookies.add(Cookie('name', 'value'));
    };
    eventSource.onHttpClientResponse = (eventSource, request, response) {
      // ...
    };
  }
  
  await for (var message in eventSource.onMessage) {
    print('Event:');
    print('  type: ${message.type}');
    print('  data: ${message.data}');
  }
}

Testing

import 'package:universal_html/controller.dart';
import 'package:test/test.dart';

void main() {
  setUp(() {
    WindowController.instance = WindowController();
  });
  
  test('test #1', () {
    // ...
  });
  
  test('test #2', () {
    // ...
  });
}

所属分类

依赖

依赖清单 9 项

源码仓库

使用此插件的项目