Quantcast
Channel: Flutter - Get image from RSS feed - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Answer by chunhunghan for Flutter - Get image from RSS feed

$
0
0

You can copy paste run full code below
You can use package https://pub.dev/packages/xml2json and parse to related Payload class , you can see class definition in full code
code snippet

http.Response response =        await http.get("http://www.rssmix.com/u/11631847/rss.xml");    if (response.statusCode == 200) {      xml2json.parse(response.body);      String jsonData = xml2json.toGData();      Payload payload = payloadFromJson(jsonData);      print(payload.rss.channel.item[0].mediaContent[1]["url"]);      for (int i = 0; i < payload.rss.channel.item.length; i++) {        var mediaContent = payload.rss.channel.item[i].mediaContent;        if (mediaContent != null && mediaContent.length >= 2) {          var mediaContentItem1 = payload.rss.channel.item[i].mediaContent[1];          if (mediaContentItem1!= null && mediaContentItem1.containsKey("url")) {            var url = mediaContentItem1["url"];            if (url != null) {              print(url);            }          }        }      }    }

output

I/flutter (27743): https://chrcph.files.wordpress.com/2020/05/tuborg-classic.jpg?w=566I/flutter (27743): https://chrcph.files.wordpress.com/2020/05/tuborg-classic.jpg?w=566I/flutter (27743): https://ousensoel.files.wordpress.com/2020/05/img_20200506_095714_846.jpg?w=1024I/flutter (27743): https://chrcph.files.wordpress.com/2020/04/45-days-extra-natural-octo.jpg?w=1024I/flutter (27743): https://chrcph.files.wordpress.com/2020/04/paulanersalvator.jpg?w=300I/flutter (27743): https://chrcph.files.wordpress.com/2020/04/pc3a5skebryg-herslev.jpg?w=640I/flutter (27743): https://chrcph.files.wordpress.com/2020/03/gb_witbier.png?w=800I/flutter (27743): https://2.gravatar.com/avatar/80b9081c0062489b95364a72652cd533?s=96&d=identicon&r=GI/flutter (27743): https://2.gravatar.com/avatar/80b9081c0062489b95364a72652cd533?s=96&d=identicon&r=GI/flutter (27743): https://ousensoel.files.wordpress.com/2020/02/img_20200103_162444_232.jpg?w=1024I/flutter (27743): https://chrcph.files.wordpress.com/2020/02/interic3b8r-the-phil-.jpg?w=550I/flutter (27743): https://chrcph.files.wordpress.com/2020/01/mikkeller-weird-weather.jpg?w=683I/flutter (27743): https://chrcph.files.wordpress.com/2020/01/chai-de-lermitage-.jpg?w=1000I/flutter (27743): https://chrcph.files.wordpress.com/2020/01/dab-frisch-vom-fass.jpg?w=474I/flutter (27743): https://2.gravatar.com/avatar/80b9081c0062489b95364a72652cd533?s=96&d=identicon&r=GI/flutter (27743): https://2.gravatar.com/avatar/80b9081c0062489b95364a72652cd533?s=96&d=identicon&r=GI/flutter (27743): https://chrcph.files.wordpress.com/2019/12/foerster-udenfor.jpg?w=1000

full code

import 'package:flutter/material.dart';import 'package:xml2json/xml2json.dart';import 'dart:convert';import 'package:http/http.dart' as http;Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));String payloadToJson(Payload data) => json.encode(data.toJson());class Payload {  String version;  String encoding;  Rss rss;  Payload({    this.version,    this.encoding,    this.rss,  });  factory Payload.fromJson(Map<String, dynamic> json) => Payload(        version: json["version"],        encoding: json["encoding"],        rss: Rss.fromJson(json["rss"]),      );  Map<String, dynamic> toJson() => {"version": version,"encoding": encoding,"rss": rss.toJson(),      };}class Rss {  String version;  List<Xmln> xmlns;  String xmlnsContent;  String xmlnsDc;  Channel channel;  Rss({    this.version,    this.xmlns,    this.xmlnsContent,    this.xmlnsDc,    this.channel,  });  factory Rss.fromJson(Map<String, dynamic> json) => Rss(        version: json["version"],        xmlns: List<Xmln>.from(json["xmlns"].map((x) => Xmln.fromJson(x))),        xmlnsContent: json["xmlns\u0024content"],        xmlnsDc: json["xmlns\u0024dc"],        channel: Channel.fromJson(json["channel"]),      );  Map<String, dynamic> toJson() => {"version": version,"xmlns": List<dynamic>.from(xmlns.map((x) => x.toJson())),"xmlns\u0024content": xmlnsContent,"xmlns\u0024dc": xmlnsDc,"channel": channel.toJson(),      };}class Channel {  Description title;  Description link;  Description description;  Description generator;  List<Item> item;  Channel({    this.title,    this.link,    this.description,    this.generator,    this.item,  });  factory Channel.fromJson(Map<String, dynamic> json) => Channel(        title: Description.fromJson(json["title"]),        link: Description.fromJson(json["link"]),        description: Description.fromJson(json["description"]),        generator: Description.fromJson(json["generator"]),        item: List<Item>.from(json["item"].map((x) => Item.fromJson(x))),      );  Map<String, dynamic> toJson() => {"title": title.toJson(),"link": link.toJson(),"description": description.toJson(),"generator": generator.toJson(),"item": List<dynamic>.from(item.map((x) => x.toJson())),      };}class Description {  String t;  Description({    this.t,  });  factory Description.fromJson(Map<String, dynamic> json) => Description(        t: json["\u0024t"],      );  Map<String, dynamic> toJson() => {"\u0024t": t,      };}class Item {  Description title;  Description link;  WfwCommentRss wfwCommentRss;  SlashComments slashComments;  dynamic mediaContent;  Description description;  Description contentEncoded;  dynamic category;  Description pubDate;  Description comments;  Guid guid;  Description dcCreator;  Description dcDate;  PostId postId;  MediaThumbnail mediaThumbnail;  Item({    this.title,    this.link,    this.wfwCommentRss,    this.slashComments,    this.mediaContent,    this.description,    this.contentEncoded,    this.category,    this.pubDate,    this.comments,    this.guid,    this.dcCreator,    this.dcDate,    this.postId,    this.mediaThumbnail,  });  factory Item.fromJson(Map<String, dynamic> json) => Item(        title: Description.fromJson(json["title"]),        link: Description.fromJson(json["link"]),        wfwCommentRss: json["wfw\u0024commentRss"] == null            ? null            : WfwCommentRss.fromJson(json["wfw\u0024commentRss"]),        slashComments: json["slash\u0024comments"] == null            ? null            : SlashComments.fromJson(json["slash\u0024comments"]),        mediaContent: json["media\u0024content"],        description: Description.fromJson(json["description"]),        contentEncoded: json["content\u0024encoded"] == null            ? null            : Description.fromJson(json["content\u0024encoded"]),        category: json["category"],        pubDate: Description.fromJson(json["pubDate"]),        comments: json["comments"] == null            ? null            : Description.fromJson(json["comments"]),        guid: Guid.fromJson(json["guid"]),        dcCreator: Description.fromJson(json["dc\u0024creator"]),        dcDate: Description.fromJson(json["dc\u0024date"]),        postId:            json["post-id"] == null ? null : PostId.fromJson(json["post-id"]),        mediaThumbnail: json["media\u0024thumbnail"] == null            ? null            : MediaThumbnail.fromJson(json["media\u0024thumbnail"]),      );  Map<String, dynamic> toJson() => {"title": title.toJson(),"link": link.toJson(),"wfw\u0024commentRss":            wfwCommentRss == null ? null : wfwCommentRss.toJson(),"slash\u0024comments":            slashComments == null ? null : slashComments.toJson(),"media\u0024content": mediaContent,"description": description.toJson(),"content\u0024encoded":            contentEncoded == null ? null : contentEncoded.toJson(),"category": category,"pubDate": pubDate.toJson(),"comments": comments == null ? null : comments.toJson(),"guid": guid.toJson(),"dc\u0024creator": dcCreator.toJson(),"dc\u0024date": dcDate.toJson(),"post-id": postId == null ? null : postId.toJson(),"media\u0024thumbnail":            mediaThumbnail == null ? null : mediaThumbnail.toJson(),      };}class Guid {  String isPermaLink;  String t;  Guid({    this.isPermaLink,    this.t,  });  factory Guid.fromJson(Map<String, dynamic> json) => Guid(        isPermaLink: json["isPermaLink"],        t: json["\u0024t"],      );  Map<String, dynamic> toJson() => {"isPermaLink": isPermaLink,"\u0024t": t,      };}class MediaContentElement {  String url;  Medium medium;  List<Xmln> xmlns;  String xmlnsMedia;  MediaTitle mediaTitle;  MediaContentElement({    this.url,    this.medium,    this.xmlns,    this.xmlnsMedia,    this.mediaTitle,  });  factory MediaContentElement.fromJson(Map<String, dynamic> json) =>      MediaContentElement(        url: json["url"],        medium: mediumValues.map[json["medium"]],        xmlns: List<Xmln>.from(json["xmlns"].map((x) => Xmln.fromJson(x))),        xmlnsMedia: json["xmlns\u0024media"],        mediaTitle: json["media\u0024title"] == null            ? null            : MediaTitle.fromJson(json["media\u0024title"]),      );  Map<String, dynamic> toJson() => {"url": url,"medium": mediumValues.reverse[medium],"xmlns": List<dynamic>.from(xmlns.map((x) => x.toJson())),"xmlns\u0024media": xmlnsMedia,"media\u0024title": mediaTitle == null ? null : mediaTitle.toJson(),      };}class MediaTitle {  Type type;  String t;  MediaTitle({    this.type,    this.t,  });  factory MediaTitle.fromJson(Map<String, dynamic> json) => MediaTitle(        type: typeValues.map[json["type"]],        t: json["\u0024t"],      );  Map<String, dynamic> toJson() => {"type": typeValues.reverse[type],"\u0024t": t,      };}enum Type { HTML }final typeValues = EnumValues({"html": Type.HTML});enum Medium { IMAGE }final mediumValues = EnumValues({"image": Medium.IMAGE});class Xmln {  Xmln();  factory Xmln.fromJson(Map<String, dynamic> json) => Xmln();  Map<String, dynamic> toJson() => {};}class MediaThumbnail {  String url;  List<Xmln> xmlns;  String xmlnsMedia;  MediaThumbnail({    this.url,    this.xmlns,    this.xmlnsMedia,  });  factory MediaThumbnail.fromJson(Map<String, dynamic> json) => MediaThumbnail(        url: json["url"],        xmlns: List<Xmln>.from(json["xmlns"].map((x) => Xmln.fromJson(x))),        xmlnsMedia: json["xmlns\u0024media"],      );  Map<String, dynamic> toJson() => {"url": url,"xmlns": List<dynamic>.from(xmlns.map((x) => x.toJson())),"xmlns\u0024media": xmlnsMedia,      };}class PostId {  Xmlns xmlns;  String t;  PostId({    this.xmlns,    this.t,  });  factory PostId.fromJson(Map<String, dynamic> json) => PostId(        xmlns: xmlnsValues.map[json["xmlns"]],        t: json["\u0024t"],      );  Map<String, dynamic> toJson() => {"xmlns": xmlnsValues.reverse[xmlns],"\u0024t": t,      };}enum Xmlns { COM_WORDPRESS_FEED_ADDITIONS_1 }final xmlnsValues = EnumValues(    {"com-wordpress:feed-additions:1": Xmlns.COM_WORDPRESS_FEED_ADDITIONS_1});class SlashComments {  List<Xmln> xmlns;  String xmlnsSlash;  String t;  SlashComments({    this.xmlns,    this.xmlnsSlash,    this.t,  });  factory SlashComments.fromJson(Map<String, dynamic> json) => SlashComments(        xmlns: List<Xmln>.from(json["xmlns"].map((x) => Xmln.fromJson(x))),        xmlnsSlash: json["xmlns\u0024slash"],        t: json["\u0024t"],      );  Map<String, dynamic> toJson() => {"xmlns": List<dynamic>.from(xmlns.map((x) => x.toJson())),"xmlns\u0024slash": xmlnsSlash,"\u0024t": t,      };}class WfwCommentRss {  List<Xmln> xmlns;  String xmlnsWfw;  String t;  WfwCommentRss({    this.xmlns,    this.xmlnsWfw,    this.t,  });  factory WfwCommentRss.fromJson(Map<String, dynamic> json) => WfwCommentRss(        xmlns: List<Xmln>.from(json["xmlns"].map((x) => Xmln.fromJson(x))),        xmlnsWfw: json["xmlns\u0024wfw"],        t: json["\u0024t"],      );  Map<String, dynamic> toJson() => {"xmlns": List<dynamic>.from(xmlns.map((x) => x.toJson())),"xmlns\u0024wfw": xmlnsWfw,"\u0024t": t,      };}class EnumValues<T> {  Map<String, T> map;  Map<T, String> reverseMap;  EnumValues(this.map);  Map<T, String> get reverse {    if (reverseMap == null) {      reverseMap = map.map((k, v) => new MapEntry(v, k));    }    return reverseMap;  }}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> {  int _counter = 0;  Xml2Json xml2json = Xml2Json();  void _incrementCounter() async {    http.Response response =        await http.get("http://www.rssmix.com/u/11631847/rss.xml");    if (response.statusCode == 200) {      xml2json.parse(response.body);      String jsonData = xml2json.toGData();      Payload payload = payloadFromJson(jsonData);      print(payload.rss.channel.item[0].mediaContent[1]["url"]);      for (int i = 0; i < payload.rss.channel.item.length; i++) {        var mediaContent = payload.rss.channel.item[i].mediaContent;        if (mediaContent != null && mediaContent.length >= 2) {          var mediaContentItem1 = payload.rss.channel.item[i].mediaContent[1];          if (mediaContentItem1!= null && mediaContentItem1.containsKey("url")) {            var url = mediaContentItem1["url"];            if (url != null) {              print(url);            }          }        }      }    }    setState(() {      _counter++;    });  }  @override  Widget build(BuildContext context) {    return Scaffold(      appBar: AppBar(        title: Text(widget.title),      ),      body: Center(        child: Column(          mainAxisAlignment: MainAxisAlignment.center,          children: <Widget>[            Text('You have pushed the button this many times:',            ),            Text('$_counter',              style: Theme.of(context).textTheme.headline4,            ),          ],        ),      ),      floatingActionButton: FloatingActionButton(        onPressed: _incrementCounter,        tooltip: 'Increment',        child: Icon(Icons.add),      ),    );  }}

Viewing all articles
Browse latest Browse all 2