Flutter Web支持插件universal_html_cpy的使用

Flutter Web支持插件universal_html_cpy的使用

感谢dint.dev,这是修复当前版本2.2.2的bug后的版本。请自行承担风险使用。

这是一个跨平台的dart:html

  • 简化跨平台开发

    • 您可以在浏览器、移动设备、桌面和服务器端VM以及Node.JS上使用此包。
    • 只需将dart:html导入替换为package:universal_html_cpy/html.dart。当应用程序在浏览器中运行时,正常的dart:html将继续被使用。
  • 广泛的HTML和XML文档处理支持

    • 解析、操作和打印DOM节点
    • 使用querySelectorAll和其他CSS查询方法查找DOM节点。
  • 事件源流支持

    • 跨平台的dart:html EventSource(“application/event-stream”)。
    • 如果您想在浏览器外自定义EventSource HTTP头,请参阅EventSourceOutsideBrowser类。

该项目根据Apache License 2.0许可发布。一些源代码是从Dart SDK中的原始dart:html采用的,在相关文件中有文档记录。

文档

类似项目

入门指南

1. 添加依赖

pubspec.yaml中添加以下内容:

dependencies:
  universal_html_cpy: ^2.2.2
2. 使用
import "package:universal_html_cpy/html.dart";

void main() {
  // 创建一个DOM树
  final divElement = DivElement();
  divElement.append(Element.tag("h1")
    ..classes.add("greeting")
    ..appendText("Hello world!"));

  // 打印外部HTML
  print(divElement.outerHtml);
  // --> <div><h1>Hello world!</h1></div>

  // 进行CSS查询
  print(divElement.querySelector("div > .greeting")!.text);
  // --> Hello world
}

示例

解析HTML

使用parseHtmlDocument

import 'package:universal_html_cpy/parsing.dart';

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

使用parseXmlDocument

import 'package:universal_html_cpy/parsing.dart';

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

使用WindowController加载一个Window

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

Future<void> main() async {
  // 加载文档
  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) {
      // 添加自定义头
      request.headers.set('Authorization', 'headerValue');
      request.cookies.add(Cookie('cookieName', 'cookieValue'));
    },
    onResponse: (HttpClientResponse response) {
      print('状态码: ${response.statusCode}');
    },
  );

  // 使用CSS查询选择顶部故事
  final titleElements = controller.document.querySelectorAll(".athing > .title");
  final topStoryTitle = titleElements.first.text;

  // 打印结果
  print("顶部Hacker News故事是: $topStoryTitle");
}
EventSource

EventSource参见mozilla.org)是一个用于读取"application/event-stream"流的浏览器API。它已被浏览器支持很长时间了。

import 'package:universal_html_cpy/html.dart';

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

EventSource请求通常通过cookies进行身份验证。如果您想添加cookies或自定义其他HTTP头,需要使用EventSourceOutsideBrowser

import 'package:universal_html_cpy/universal_html_cpy.dart';
import 'dart:io' show Cookie;

Future<void> main() async {
  final eventSource = EventSource('http://example.com/events');

  // 下面的代码块不会在浏览器中执行。
  // 因为编译器可以推断出`EventSourceOutsideBrowser`实例永远不会被构造,
  // 所以它也不会出现在JavaScript中。
  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('事件:');
    print('  类型: ${message.type}');
    print('  数据: ${message.data}');
  }
}
测试
import 'package:universal_html_cpy/controller.dart';
import 'package:test/test.dart';

void main() {
  setUp(() {
    WindowController.instance = WindowController();
  });

  test('测试#1', () {
    // ...
  });

  test('测试#2', () {
    // ...
  });
}

更多关于Flutter Web支持插件universal_html_cpy的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Web支持插件universal_html_cpy的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter Web项目中,universal_html_cpy 是一个对 Dart 的 dart:html 库进行扩展和修改的库,提供了更多的功能和更好的兼容性。这对于需要在 Flutter Web 上使用 HTML API 的开发者来说非常有用。以下是如何在 Flutter Web 项目中使用 universal_html_cpy 的一个简单示例。

步骤 1: 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 universal_html_cpy 的依赖。

dependencies:
  flutter:
    sdk: flutter
  universal_html_cpy: ^x.y.z  # 请替换为最新版本号

然后运行 flutter pub get 来获取依赖。

步骤 2: 导入库

在你的 Dart 文件中导入 universal_html_cpy。注意,由于 Flutter Web 和其他平台(如移动)的兼容性,你可能需要使用条件导入。

import 'package:universal_html/html.dart' as html;
import 'package:flutter/foundation.dart' show kIsWeb;

步骤 3: 使用示例

下面是一个简单的示例,展示如何在 Flutter Web 项目中使用 universal_html_cpy 来操作 DOM 元素。

import 'package:flutter/material.dart';
import 'package:universal_html/html.dart' as html;
import 'package:flutter/foundation.dart' show kIsWeb;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Universal HTMLCPY Example'),
        ),
        body: Center(
          child: kIsWeb
              ? WebContent()
              : Text('This example only works on web.'),
        ),
      ),
    );
  }
}

class WebContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        // 创建一个新的div元素
        html.DivElement newDiv = html.DivElement()
          ..text = 'Hello, this is a new div!';
          
        // 将新创建的div元素添加到body中
        html.document.body?.append(newDiv);
      },
      child: Text('Add Div to Body'),
    );
  }
}

解释

  1. 条件导入:使用 kIsWeb 来判断当前是否在 Web 平台上运行,这样可以在不同平台上提供不同的实现。
  2. 操作 DOM:通过 html.DivElement 创建一个新的 div 元素,并使用 html.document.body?.append(newDiv) 将其添加到网页的 body 中。

注意事项

  • 确保你的 Flutter 环境已经配置好对 Web 的支持。
  • universal_html_cpy 是一个对 dart:html 的扩展,因此它只能在 Web 平台上工作。在移动或其他平台上运行时,应该提供替代逻辑。
  • 始终检查库的最新版本和文档,以确保使用最新的功能和修复。

通过上述步骤,你可以在 Flutter Web 项目中有效地使用 universal_html_cpy 来操作 DOM 和利用 HTML API。

回到顶部