Flutter网页内容渲染插件adjusted_html_view_web的使用

Flutter网页内容渲染插件adjusted_html_view_web的使用

adjusted_html_view_web

pub package

此插件仅适用于Web平台。

特性

该插件在Web平台上提供了更自然的HTML显示方式。由于它是通过Platform View而不是iframe来显示,因此你将获得以下好处:

  • 根据HTML内容的高度进行显示
    • 例如:可以在Column中混合HTML内容
  • 文本选择
  • 自然滚动
  • 自定义CSS

尝试在线演示: https://organic-nailer.github.io/adjusted_html_view_web/#/

此插件适用场景

  • 使用Flutter开发Web应用的开发者
  • 需要使用HTML来展示无法用Widget表达的部分
  • 需要显示通过CMS等传递的富文本内容

此插件不适用场景

  • 在移动或桌面平台上使用Flutter的开发者
  • 需要显示特定网站的开发者
  • 需要使用WebView来显示内容的开发者

使用方法

使用AdjustedHtmlView并传入富文本字符串到htmlText属性。 可以通过HtmlValidator来选择安全级别。

const sampleRichText = """
<h1 id="hf19cd910e2">Heading 1</h1>
<p>Flutter is an open-source UI software development kit created by Google.</p>
""";

AdjustedHtmlView(
  htmlText: sampleRichText,
  htmlValidator: HtmlValidator.loose(),
)

其他信息

目前不可能实现的功能

  • 在一个屏幕上放置多个AdjustedHtmlView

完整示例代码

import 'package:adjusted_html_view_web/adjusted_html_view_web.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: Center(
          child: SingleChildScrollView(
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 600),
              child: Column(
                children: [
                  const Text("AdjustedHtmlViewSample", style: TextStyle(fontSize: 40)),
                  const SizedBox(height: 20),
                  Card(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: AdjustedHtmlView(
                        htmlText: sampleRichText,
                        htmlValidator: HtmlValidator.unsafe(),
                      ),
                    ),
                  ),
                  const SizedBox(height: 20),
                  const Text("Footer", style: TextStyle(fontSize: 40)),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

const sampleRichText = """
<h1 id="hf19cd910e2">Heading 1</h1>
<h2 id="hb71f3638bb">Heading 2</h2>
<h3 id="h055e8f9099">Heading 3</h3>
<h4 id="h8c98ba6ad9">Heading 4</h4>
<h5 id="he1b3d42007">Heading 5</h5>
<p>Flutter is an open-source UI software development kit created by Google. It is used to develop cross platform applications for Android, iOS, Linux, Mac, Windows, Google Fuchsia, Web platform, and the web from a single codebase.
<br>This is a <span style="font-size: 2.5em">Bigger Text</span>.<br>This is a <span style="font-size: 1.5em">Big Text</span>.<br>This is a <span style="font-size: 0.75em">Small Text</span>.<br>This text contains <strong>bold</strong>, <em>italic</em>, <u>underline</u>, <s>strikethrough</s>, <span style="background-color:#edad0b">background colored text</span>, <span style="color:#009250">colored text</span>, sub<sub>script</sub>, super<sup>script</sup> and <a href="unsafe:fastriver.dev">hyperlinks</a>.
<br><code>somethingDo()</code> is awesome function.
<br>align left</p>
<p style="text-align:center">align center</p>
<p style="text-align:right">align right</p>
<p style="text-align:justify">align stretch</p>
<blockquote>This is Quoted Text.</blockquote>
<pre><code>void main(List&lt;String&gt; args) {
    print("This is a code block");
}
</code></pre>
<p>
<br><img src="https://via.placeholder.com/800x100?text=This+is+an+image" alt="This is an image.">
<br></p>
<blockquote class="twitter-tweet"><p lang="ja" dir="ltr">天才なのでFlutter WebでWebViewを大きさぴったりにできるようになった<a href="https://t.co/zVpdpjDciL">https://t.co/zVpdpjDciL</a></p>&mdash; Fastriver ([@Fastriver_org](/user/Fastriver_org)) <a href="https://twitter.com/Fastriver_org/status/1492411759743086593?ref_src=twsrc%5Etfw">February 12, 2022</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<p><br></p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/fq4N0hgOWzU" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<p><br></p>
<ol><li>ONE</li><li>TWO<ol><li>TWO-A</li></ol></li><li>THREE</li></ol>
<p><br></p>
<ul><li>Android</li><li>iOS</li><li>Web<ul><li>PWA</li></ul></li></ul>
""";

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用adjusted_html_view_web插件来渲染网页内容的示例代码。这个插件主要用于在Flutter的Web平台上渲染HTML内容。

首先,确保你已经在pubspec.yaml文件中添加了adjusted_html_view_web依赖:

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

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

接下来,在你的Flutter项目中,你可以创建一个Web特定的页面来使用adjusted_html_view_web插件。以下是一个完整的示例:

import 'package:flutter/material.dart';
import 'package:adjusted_html_view_web/adjusted_html_view_web.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Web HTML Rendering Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HtmlRenderingPage(),
    );
  }
}

class HtmlRenderingPage extends StatelessWidget {
  final String htmlContent = """
  <html>
  <head>
    <title>Sample HTML</title>
    <style>
      body { font-family: Arial, sans-serif; }
      h1 { color: #333; }
      p { color: #666; }
    </style>
  </head>
  <body>
    <h1>Hello, Flutter Web!</h1>
    <p>This is a sample HTML content rendered using adjusted_html_view_web plugin.</p>
  </body>
  </html>
  """;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('HTML Rendering Demo'),
      ),
      body: Center(
        child: Builder(
          builder: (context) {
            // Check if the platform is web
            if (kIsWeb) {
              return AdjustedHtmlViewWeb(
                htmlData: htmlContent,
              );
            } else {
              // Handle non-web platforms if necessary
              return Text('This demo is only for Web platform.');
            }
          },
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个HtmlRenderingPage页面。在这个页面中,我们使用AdjustedHtmlViewWeb小部件来渲染HTML内容。注意,我们使用了kIsWeb常量来确保这个逻辑只在Web平台上运行。

注意事项

  1. 平台检查adjusted_html_view_web插件是为Web平台设计的,因此在非Web平台上(如iOS和Android),你需要进行适当的处理,例如显示一个占位符或重定向到其他页面。
  2. 样式和脚本:HTML内容中的样式和脚本会在渲染时被应用,但请注意,由于安全和性能原因,某些内联脚本和样式可能会被限制或忽略。
  3. 最新版本:请确保使用adjusted_html_view_web的最新版本,因为插件的功能和API可能会随着版本更新而变化。

这样,你就可以在Flutter Web应用中渲染HTML内容了。希望这个示例对你有帮助!

回到顶部