【问题标题】:How to filter img tag from the html in flutter如何在flutter中从html中过滤img标签
【发布时间】:2020-08-23 06:53:03
【问题描述】:

我正在使用 WordPress rest API 在颤振中制作应用程序。在 WordPress rest API post 中有一个名为 content 的属性,该属性具有进一步的属性呈现,如 Json 所示。在呈现的属性中有一个 html 标签。我只想从那里过滤 img 标签。我如何在 dart 或 php 中实现这一点?

        "id": 1660,
        "link": "http://localhost/soledesign/bill-baber/",
        "title": {
            "rendered": "Bill Baber"
        },
        "content": {
            "rendered": "<h2>Bill Baber Knitwear opened our doors for the first time back in 1977 and have been producing the finest Scottish knitwear ever since.</h2>\n<p>Helen &amp; Bill Baber design and produce the whole collection themselves, with a little help from time to time. The collection includes mostly ladies wear, with some unisex styles, sorry guys! You’ll find full length silk jackets, luxuriously soft cashmere shawls, lightweight linen tops and stunning accessories to pep up any outfit. The widest selection can be found in store at <a href=\"https://billbaber.com/contact-us/\">66 Grassmarket</a>, however we do have a collection available <a href=\"https://billbaber.com/shop/\">online</a> for you to enjoy and we even supply other <a href=\"https://billbaber.com/stockists/\">retailers</a> all over the world!</p>\n<p>On this site you will see garments that we carry in stock or produce to order. in some cases we may hold a little stock ready to go, but generally each items is made from scratch when you order it. In store we have a boutique collection many of which simply cannot be reproduced, sometimes the yarn has run out or the style was a one off creation.</p>\n<p>&nbsp;</p>\n<p><img src=\"https://billbaber.com/wp-content/uploads/2019/09/crail_silver-190x285.jpg\" alt=\"Crail Top\" /><img src=\"https://billbaber.com/wp-content/uploads/2019/09/liscannor_crew-190x285.jpg\" alt=\"Crew Jumper\" /><img src=\"https://billbaber.com/wp-content/uploads/2017/09/t_alt_dne-190x285.jpg\" alt=\"Alto Top\" /><img src=\"https://billbaber.com/wp-content/uploads/2017/09/t_dtt_sge-190x285.jpg\" alt=\"Dot\" /></p>\n<p>&nbsp;</p>\n",
            "protected": false
        },
        "excerpt": {
            "rendered": "<p>Bill Baber Knitwear opened our doors for the first time back in 1977 and have been producing the finest Scottish knitwear ever since. Helen &amp; Bill Baber design and produce the whole collection themselves, with a little help from time to time. The collection includes mostly ladies wear, with some unisex styles, sorry guys! You’ll [&hellip;]</p>\n",
            "protected": false
        },
        "author": 83
    },

【问题讨论】:

    标签: php html json wordpress flutter


    【解决方案1】:

    您可以在下面复制粘贴运行完整代码
    你可以使用包https://pub.dev/packages/html
    第一步:去掉特殊字符,解析json字符串,可以看到Payload类的完整代码

    String result = jsonString.replaceAll("\n", "");
    Payload payload = payloadFromJson(result);
    

    第 2 步:通过 querySelectorAll("img") 获取 DOM Element

    import 'package:html/parser.dart' show parse;
    import 'package:html/dom.dart' as dom;
    ...    
    
    var document = parse(payload.content.rendered);
    var imgList = document.querySelectorAll("img");
    
    for (dom.Element img in imgList) {
      print(img.attributes["src"]);
      print(img.toString());
    }
    

    输出

    I/flutter (11892): https://billbaber.com/wp-content/uploads/2019/09/crail_silver-190x285.jpg
    I/flutter (11892): https://billbaber.com/wp-content/uploads/2019/09/liscannor_crew-190x285.jpg
    I/flutter (11892): https://billbaber.com/wp-content/uploads/2017/09/t_alt_dne-190x285.jpg
    I/flutter (11892): https://billbaber.com/wp-content/uploads/2017/09/t_dtt_sge-190x285.jpg
    

    工作演示

    完整代码

    import 'package:flutter/material.dart';
    import 'package:html/parser.dart' show parse;
    import 'package:html/dom.dart' as dom;
    import 'dart:convert';
    
    Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
    
    String payloadToJson(Payload data) => json.encode(data.toJson());
    
    class Payload {
      int id;
      String link;
      Title title;
      Content content;
      Content excerpt;
      int author;
    
      Payload({
        this.id,
        this.link,
        this.title,
        this.content,
        this.excerpt,
        this.author,
      });
    
      factory Payload.fromJson(Map<String, dynamic> json) => Payload(
            id: json["id"],
            link: json["link"],
            title: Title.fromJson(json["title"]),
            content: Content.fromJson(json["content"]),
            excerpt: Content.fromJson(json["excerpt"]),
            author: json["author"],
          );
    
      Map<String, dynamic> toJson() => {
            "id": id,
            "link": link,
            "title": title.toJson(),
            "content": content.toJson(),
            "excerpt": excerpt.toJson(),
            "author": author,
          };
    }
    
    class Content {
      String rendered;
      bool protected;
    
      Content({
        this.rendered,
        this.protected,
      });
    
      factory Content.fromJson(Map<String, dynamic> json) => Content(
            rendered: json["rendered"],
            protected: json["protected"],
          );
    
      Map<String, dynamic> toJson() => {
            "rendered": rendered,
            "protected": protected,
          };
    }
    
    class Title {
      String rendered;
    
      Title({
        this.rendered,
      });
    
      factory Title.fromJson(Map<String, dynamic> json) => Title(
            rendered: json["rendered"],
          );
    
      Map<String, dynamic> toJson() => {
            "rendered": rendered,
          };
    }
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      Future<List<String>> _future;
    
      Future<List<String>> _getData() {
        String jsonString = r'''
        {
        "id": 1660,
            "link": "http://localhost/soledesign/bill-baber/",
            "title": {
                "rendered": "Bill Baber"
            },
            "content": {
                "rendered": "<h2>Bill Baber Knitwear opened our doors for the first time back in 1977 and have been producing the finest Scottish knitwear ever since.</h2>\n<p>Helen &amp; Bill Baber design and produce the whole collection themselves, with a little help from time to time. The collection includes mostly ladies wear, with some unisex styles, sorry guys! You’ll find full length silk jackets, luxuriously soft cashmere shawls, lightweight linen tops and stunning accessories to pep up any outfit. The widest selection can be found in store at <a href=\"https://billbaber.com/contact-us/\">66 Grassmarket</a>, however we do have a collection available <a href=\"https://billbaber.com/shop/\">online</a> for you to enjoy and we even supply other <a href=\"https://billbaber.com/stockists/\">retailers</a> all over the world!</p>\n<p>On this site you will see garments that we carry in stock or produce to order. in some cases we may hold a little stock ready to go, but generally each items is made from scratch when you order it. In store we have a boutique collection many of which simply cannot be reproduced, sometimes the yarn has run out or the style was a one off creation.</p>\n<p>&nbsp;</p>\n<p><img src=\"https://billbaber.com/wp-content/uploads/2019/09/crail_silver-190x285.jpg\" alt=\"Crail Top\" /><img src=\"https://billbaber.com/wp-content/uploads/2019/09/liscannor_crew-190x285.jpg\" alt=\"Crew Jumper\" /><img src=\"https://billbaber.com/wp-content/uploads/2017/09/t_alt_dne-190x285.jpg\" alt=\"Alto Top\" /><img src=\"https://billbaber.com/wp-content/uploads/2017/09/t_dtt_sge-190x285.jpg\" alt=\"Dot\" /></p>\n<p>&nbsp;</p>\n",
                "protected": false
            },
            "excerpt": {
                "rendered": "<p>Bill Baber Knitwear opened our doors for the first time back in 1977 and have been producing the finest Scottish knitwear ever since. Helen &amp; Bill Baber design and produce the whole collection themselves, with a little help from time to time. The collection includes mostly ladies wear, with some unisex styles, sorry guys! You’ll [&hellip;]</p>\n",
                "protected": false
            },
            "author": 83
    }
        ''';
    
        String result = jsonString.replaceAll("\n", "");
        Payload payload = payloadFromJson(result);
        var document = parse(payload.content.rendered);
        var imgList = document.querySelectorAll("img");
        List<String> imageList = [];
        for (dom.Element img in imgList) {
          print(img.attributes["src"]);
          imageList.add(img.attributes["src"]);
        }
        return Future.value(imageList);
      }
    
      @override
      void initState() {
        _future = _getData();
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text(widget.title),
            ),
            body: FutureBuilder<List<String>>(
                future: _getData(),
                builder: (BuildContext context, AsyncSnapshot<List<String>> snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.none:
                      return Text('Input a URL to start');
                    case ConnectionState.waiting:
                      return Center(child: CircularProgressIndicator());
                    case ConnectionState.active:
                      return Text('');
                    case ConnectionState.done:
                      if (snapshot.hasError) {
                        return Text(
                          '${snapshot.error}',
                          style: TextStyle(color: Colors.red),
                        );
                      } else {
                        return ListView.builder(
                            itemCount:
                                snapshot.data.length,
                            itemBuilder: (context, index) {
                              return ListTile(
                                title: Text(snapshot.data[index]),
                              );
                            });
                      }
                  }
                }));
      }
    }
    

    【讨论】:

    • 有没有办法在不将 jsonString 转换为原始字符串的情况下过滤图像,因为我从 api 获取值并将其存储在变量中。@chunhunghan
    • 不将 json 转换为模型 Payload。你不能用 document.querySelectorAll("img"); 解析它
    • 很高兴为您提供帮助。如果对您有帮助,请将其标记为答案。谢谢。
    • 我可以使用 ListView.builder() 代替 for in 循环吗?
    • 我已经更新了完整的代码和工作演示。你可以检查一下。
    猜你喜欢
    • 2012-10-20
    • 2018-07-20
    • 2019-05-20
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多