首页 > 解决方案 > Laravel 搜索结果包含 HTML 并在 Flutter UI 中呈现

问题描述

我有一个颤振应用程序,它连接到基于 Laravel 构建的数据库。本质上,我们的用户将拥有个人资料,他们的个人资料将与某些类型的帖子相匹配。当这些帖子在前端匹配并显示时(我认为它们以 JSON 格式返回,但不是 100% 确定),我们希望这些结果中的某些字段包含一些在 Flutter UI 中呈现的 html。

像 ul、li、换行符、p 之类的东西,也许还有粗体。没什么大不了的。为了做到这一点,在这些文本字段中阅读的正确方法是什么?

标签: htmllaravelparsingflutter

解决方案


我认为,有两种可能的解决方案。

第一个解决方案:

尝试在 pubspec.ymal 中添加以下依赖项

dependencies:
 flutter_html_view: ^0.5.11

并像这样使用它:

import 'package:flutter_html_view/flutter_html_view.dart';

String html = '<body>Hello world! <a href="#">HTML5 rocks!</a> <ul><li>test</li></ul>';

new HtmlView(
  data: html,
  baseURL: "", // optional, type String
  onLaunchFail: (url) { // optional, type Function
    print("launch $url failed");
  },
  scrollable: false
)

支持的标签有:

  • p
  • 时间
  • b
  • 图像
  • 视频
  • h1、h2、h3、h4、h5、h6

笔记

这个插件将一些html标签转换为flutter小部件这个插件不支持渲染完整的html代码(flutter中没有内置对web渲染的支持)

第二种解决方案:

基本上你需要将你的 html 转换为 Markdown。

dependencies
  html2md: "^0.3.2"
  flutter_markdown: "^0.2.0"

代码类似于

//importing packages
import 'package:html2md/html2md.dart' as html2md;
import 'package:flutter_markdown/flutter_markdown.dart';

// get the html string
static String html = '<h1>This is heading 1</h1> <h2>This is heading 2</h2><h3>This is heading 3</h3><h4>This is heading 4</h4><h5>This is heading 5</h5><h6>This is heading 6</h6><img alt="Test Image" src="https://i.ytimg.com/vi/RHLknisJ-Sg/maxresdefault.jpg" /><p>This paragraph contains a lot of lines in the source code, but the browser ignores it.</p>';

//convert it
String markdown = html2md.convert(html);

要在小部件上使用它,只需执行以下操作:

new MarkdownBody(
  data: markdown,
)

推荐阅读