Flutter网页渲染插件custom_universal_html的使用

Flutter网页渲染插件custom_universal_html的使用

Introduction

一个跨平台的dart:html库:

  • 简化跨平台开发

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

    • 解析、操作和打印 <a href="https://pub.dev/documentation/custom_universal_html/latest/custom_universal_html/Node-class.html">DOM节点</a>
    • 使用 <a href="https://pub.dev/documentation/custom_universal_html/latest/custom_universal_html/querySelectorAll.html">querySelectorAll</a> 和其他CSS查询方法查找DOM节点。
    • 提交表单等。
  • EventSource流支持

    • 实现了 <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource" rel="ugc">EventSource API</a>

该项目根据Apache License 2.0授权。部分源代码来自原始的 <a href="https://github.com/dart-lang/sdk/tree/master/tools/dom" rel="ugc">dart:html</a>,并在相关文件中进行了记录。

Documentation

Similar projects

Getting started

1. 添加依赖

pubspec.yaml中添加以下依赖:

dependencies:
  custom_universal_html: ^2.0.8

2. 使用

以下是一个简单的示例,展示如何创建DOM树并操作它:

import 'package:custom_universal_html/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!
}

实现的API

Summary

  • 文档节点类

  • DOM解析

    • 使用element.innerHtml设置器,DomParserpackage:custom_universal_html/parsing.dart
    • HTML解析使用 <a href="https://pub.dev/packages/html">package:html</a>,CSS解析使用 <a href="https://pub.dev/packages/csslib">package:csslib</a>,XML解析使用我们自己的解析器。
  • DOM打印

    • 使用element.innerHtmlelement.outerHtml
  • DOM事件

    • 例如,element.onClick.listen(...) 接收 element.click() 的调用。
  • CSS类 (CssStyleDeclaration 等)

  • 大多数CSS查询

Examples

解析HTML

使用 <a href="https://pub.dev/documentation/custom_universal_html/latest/custom_universal_html.parsing/parseHtmlDocument.html">parseHtmlDocument</a>

import 'package:custom_universal_html/parsing.dart';

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

解析XML

使用 <a href="https://pub.dev/documentation/custom_universal_html/latest/custom_universal_html.parsing/parseXmlDocument.html">parseXmlDocument</a>

import 'package:custom_universal_html/parsing.dart';

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

抓取网站

通过 <a href="https://pub.dev/documentation/custom_universal_html/latest/custom_universal_html.controller/WindowController-class.html">WindowController</a> 加载文档:

import 'package:custom_universal_html/controller.dart';

Future<void> main() async {
  // 加载文档
  final controller = WindowController();
  await controller.openHttp(uri: Uri.parse("https://news.ycombinator.com/"));

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

  // 打印结果
  print("Top Hacker News story is: $topStoryTitle");
}

完整示例代码

以下是完整的示例代码,展示如何使用custom_universal_html库来创建和操作DOM:

// 文件路径: example/example.dart

import 'package:custom_universal_html/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!
}

运行上述代码后,您将看到控制台输出以下内容:

<div><h1>Hello world!</h1></div>
Hello world!

更多关于Flutter网页渲染插件custom_universal_html的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter网页渲染插件custom_universal_html的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


custom_universal_html 是一个用于在 Flutter 中渲染 HTML 内容的插件,特别是在 Web 和桌面平台上。它提供了一个统一的 API,使得开发者可以在不同的平台上使用相同的代码来渲染 HTML 内容。

安装

首先,你需要在 pubspec.yaml 文件中添加 custom_universal_html 依赖:

dependencies:
  flutter:
    sdk: flutter
  custom_universal_html: ^latest_version

然后运行 flutter pub get 来安装依赖。

基本用法

  1. 导入包

    import 'package:custom_universal_html/custom_universal_html.dart';
    
  2. 渲染 HTML 内容

    class HtmlViewer extends StatelessWidget {
      final String htmlContent;
    
      HtmlViewer({required this.htmlContent});
    
      @override
      Widget build(BuildContext context) {
        return UniversalHtml(
          html: htmlContent,
        );
      }
    }
    
  3. 使用 HtmlViewer 组件

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('HTML Viewer'),
            ),
            body: HtmlViewer(
              htmlContent: '<h1>Hello, World!</h1><p>This is an example of HTML content.</p>',
            ),
          ),
        );
      }
    }
    

高级用法

  1. 自定义样式: 你可以通过 style 参数来自定义 HTML 内容的样式。

    UniversalHtml(
      html: '<h1>Hello, World!</h1>',
      style: '''
        h1 {
          color: blue;
          font-size: 24px;
        }
      ''',
    );
    
  2. 处理链接点击: 你可以通过 onLinkTap 参数来处理链接的点击事件。

    UniversalHtml(
      html: '<a href="https://flutter.dev">Visit Flutter</a>',
      onLinkTap: (url) {
        print('Link tapped: $url');
        // 在这里处理链接点击事件,例如打开浏览器
      },
    );
    
  3. 自定义错误处理: 你可以通过 onError 参数来处理渲染过程中的错误。

    UniversalHtml(
      html: '<invalid>HTML</invalid>',
      onError: (error) {
        print('Error rendering HTML: $error');
      },
    );
回到顶部