Как показать html-строку во флаттере текстового виджета

Как показать строку тега html во флаттере, я пробовал плагин, но он не работает.

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

Это мой html

“Follow<a class='sup'><sup>pl</sup></a> what was sent down to you from your Lord, and do not follow other guardians apart from Him. Little do <span class='h'>you remind yourselves</span><a class='f'><sup f=2437>1</sup></a>.”   

я использую flutter_html_view: "^ 0.5.10" этот плагин

Можете выложить флаттер-версию?

Nagendra Badiganti 17.12.2018 14:18

@NagendraBadiganti Flutter (бета-версия канала, v1.0.0, в Mac OS X 10.13.6 17G65, локаль en-IN)

Deepak Gehlot 17.12.2018 14:29

проверьте с помощью зависимости flutter_html: ^ 0.8.2. он отлично работает у меня все время. Я только что отправил ответ. Если это сработает, опустите большой палец вверх.

Nagendra Badiganti 17.12.2018 14:33

Этот плагин просто не может хорошо отображать ваш html-код. Прочитать документыThis plugin does't support rendering full html code

shadowsheep 17.12.2018 14:41

Плагин webview_flutter от Flutter Team у меня работает очень хорошо: stackoverflow.com/a/55149298

Suragch 13.03.2019 21:57

Я думаю, что этого плагина больше нет

Elia Weiss 28.01.2020 15:51
39
6
80 575
6

Ответы 6

У этого плагина нет никаких проблем, я просто создал образец с вашим HTML, и он отлично работает. Попробуйте заменить на приведенный ниже фрагмент и посмотрите, работает ли это.

dependencies:
  flutter_html: ^0.8.2
        

и импорт и код для рендеринга html

import 'package:flutter_html/flutter_html.dart';
import 'package:html/dom.dart' as dom;


 body: new Center(
            child: SingleChildScrollView(
              child: Html(
                data: """
                <div>Follow<a class='sup'><sup>pl</sup></a> 
                  Below hr
                    <b>Bold</b>
                <h1>what was sent down to you from your Lord</h1>, 
                and do not follow other guardians apart from Him. Little do 
                <span class='h'>you remind yourselves</span><a class='f'><sup f=2437>1</sup></a></div>
                """,
                padding: EdgeInsets.all(8.0),
                onLinkTap: (url) {
                  print("Opening $url...");
                },
                customRender: (node, children) {
                  if (node is dom.Element) {
                    switch (node.localName) {
                      case "custom_tag": // using this, you can handle custom tags in your HTML 
                        return Column(children: children);
                    }
                  }
                },
              ),
            ),
          )

знаете ли вы другой плагин помимо flutter_html, этот плагин не может отображать таблицу и не может быть выбран, спасибо

MNFS 20.04.2020 11:59

flutter_html теперь поддерживает <table>, <tbody>, <td>, <th>, <tr>. Единственное, что он не поддерживает, - это <style>, что может быть проблемой для некоторых людей.

Jet.Black.Pope 05.05.2020 17:54

данные html преобразуют теги div в промежутки при проверке. Мне нужно сохранить div и id div.

Golden Lion 17.08.2020 19:41

вы можете использовать таблицу данных флаттера для отображения информации таблицы в строках данных, столбцах данных и ячейках данных

Golden Lion 17.08.2020 19:43

Привет, я хотел бы реализовать это в сети Flutter, знаете ли вы какие-нибудь доступные пакеты?

uyhaW 27.11.2020 08:21

как я могу использовать в нем такие свойства, как overflow, maxlines ??

Shadab Hashmi 12.05.2021 15:16

Не используйте flutter_html_view, чтение в документация:

Supported Tags

  • p
  • em
  • b
  • img
  • video
  • h1,
  • h2,
  • h3,
  • h4,
  • h5,
  • h6
  • Note

This plugin converts some of the html tags to flutter widgets This plugin does't support rendering full html code (there is no built in support for web rendering in flutter)

Так что он просто плохо отображает ваш html, потому что не может.

Но вы можете найти и другие пулугины, например flutter_html.

https://github.com/Sub6Resources/flutter_html

и дайте им попробовать, чтобы увидеть, лучше ли они работают.

ОБНОВИТЬ

В pubspec.yaml я добавил

dependencies:
  flutter_html: ^0.8.2

а мой main.dart

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


void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  var html = "Follow<a class='sup'>pl</a> what was sent down to you from your Lord, and do not follow other guardians apart from Him. Little do <p class='h'>you remind yourselves</p><a class='f'><sup f=2437>1</a>.";


  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Html(
              data: html,
              ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Можете ли вы показать мне свой код, я проверил, но PL не отображается, как ваш.

Deepak Gehlot 17.12.2018 15:11

@DeepakGehlot уверен. Я обновил свой ответ. Я только что изменил стандартный проект Flutter Activity, чтобы проверить его.

shadowsheep 17.12.2018 15:29

Используйте плагин flutter_webview_plugin

пример:

new WebviewScaffold(
              url: new Uri.dataFromString('<html><body>hello world</body></html>', mimeType: 'text/html').toString()

Веб-просмотр внутри настраиваемого прямоугольника

final flutterWebviewPlugin = new FlutterWebviewPlugin();

flutterWebviewPlugin.launch(url,
  fullScreen: false,
  rect: new Rect.fromLTWH(
    0.0,
    0.0,
    MediaQuery.of(context).size.width,
    300.0,
  ),
);

WebView нельзя добавить в дерево виджетов, не так ли. Или я что-то упускаю?

shadowsheep 17.12.2018 20:17

Вы проверили пример кода? github.com/fluttercommunity/flutter_webview_plugin/blob/mast‌ er /…

Shyju M 18.12.2018 05:07

это Scaffold, а не виджет, если вы хотите вставить в существующую страницу, вы можете использовать веб-просмотр в прямоугольнике flutterWebViewPlugin.launch (selectedUrl, rect: Rect.fromLTWH (0.0, 0.0, MediaQuery.of (context). size.width, 300.0), userAgent: kAndroidUserAgent,);

Shyju M 18.12.2018 05:10

Ага, у меня было :-). Это причина моего вопроса Предупреждение: Веб-просмотр не интегрирован в дерево виджетов, это собственный вид поверх флаттер-представления. вы не сможете использовать закуски, диалоги ... В примере кода это используется как страница не в дереве виджетов.

shadowsheep 18.12.2018 05:10

создайте свой собственный каркас и визуализируйте веб-просмотр внутри прямоугольника, затем вы можете использовать закуски, диалог и т. д.

Shyju M 18.12.2018 05:14

Рад это знать, спасибо. Но я думаю, что это не вопрос ОП. Вам не казалось, что кода должно быть слишком много, чтобы получить то, что он просит?

shadowsheep 18.12.2018 05:18

невозможно загрузить этот html с помощью этого плагина, у меня есть пользователь WebviewScaffold только для тестирования, и его не загружает, показывая ошибку «строка содержит недопустимые символы». <html> <body> Следуйте <a class='sup'> <sup> pl </sup> </a> тому, что было ниспослано вам от вашего Господа, и не следуйте за другими хранителями, кроме Него. Мало что <span class = 'h'> вы напоминаете себе </span> <a class='f'> <sup f = 2437> 1 </sup> </a>. </body> </html>

Deepak Gehlot 18.12.2018 06:22

вот рабочий код gist.github.com/shyjuzz/d6fd5562f97b36b0e2eb957eff3c687a

Shyju M 19.12.2018 06:13

Я получаю Contains invalid characters.

Elia Weiss 14.02.2021 16:28

Я только что сделал следующее, и он отлично работает.

  1. Добавьте flutter_html в свой файл pubspec.yaml.
dependencies:
  flutter:
    sdk: flutter
  flutter_html: ^0.8.2 
  1. Выполните следующую команду, чтобы обновить пакеты.

flutter pub get

  1. Импортировать flutter_html

import 'package:flutter_html/flutter_html.dart';

  1. Замените текстовый виджет на виджет HTML.
   child: 
   // Text(
   //   "Hello Programmer",
   //   style: TextStyle(fontSize: 18),
   // ),
   Html(data:"<p>Hello <b>Flutter</b><p>"),

Добавьте в файл pubspec.yaml следующее:

dependencies:
  flutter_html:

Поддерживаемые в настоящее время HTML-теги:

a, abbr, аббревиатура, адрес, статья, в сторону, b, bdi, bdo, big, цитата, тело, br, подпись, цитировать, код, данные, dd, del, dfn, div, dl, dt, em, figcaption, рисунок, нижний колонтитул, h1, h2, h3, h4, h5, h6, header, hr, i, img, ins, kbd, li, main, mark, nav, noscript, ol, p, pre, q, rp, rt, ruby, s, samp, section, small, span, strike, strong, sub, sup, table, tbody, td, template, tfoot, th, thead, time, tr, tt, u, ul, var

Пример использования:

Column(
   mainAxisAlignment: MainAxisAlignment.start,
   crossAxisAlignment: CrossAxisAlignment.start,
   children: [
      new Html(
         data: "<b>Welcome</b>,
          defaultTextStyle: TextStyle(fontSize: 15),
       ),
     ],
)

В pubspec.yml добавьте следующее:

dependencies:
  flutter_html:

Затем запустите:

flutter clean && flutter pub get

Наконец, добавьте такой код:

import 'package:flutter_html/flutter_html.dart';
.
.
.
body: Center( Html(
      data: """
            <div>This is the start of a div
              <a class='sup'><sup>a sup</sup></a> 
              and after sub
              <b>Bold</b>
              <h1>This is a header with number 1557</h1> 
              A text and 
            <span class='h'>some stuff</div>
            """,
    ),)

Screenshot from phone

До сих пор он отлично работал как на мобильных устройствах, так и в Интернете.

Другие вопросы по теме