this is my model:
// To parse this JSON data, do
//
// final economylistXml = economylistXmlFromJson(jsonString);
import 'dart:convert';
EconomylistXml economylistXmlFromJson(String str) => EconomylistXml.fromJson(json.decode(str));
String economylistXmlToJson(EconomylistXml data) => json.encode(data.toJson());
class EconomylistXml {
EconomylistXml({
required this.rss,
});
Rss rss;
factory EconomylistXml.fromJson(Map<String, dynamic> json) => EconomylistXml(
rss: Rss.fromJson(json["rss"]),
);
Map<String, dynamic> toJson() => {
"rss": rss.toJson(),
};
}
class Rss {
Rss({
required this.empty,
required this.channel,
});
Empty empty;
Channel channel;
factory Rss.fromJson(Map<String, dynamic> json) => Rss(
empty: Empty.fromJson(json["\u0024"]),
channel: Channel.fromJson(json["channel"]),
);
Map<String, dynamic> toJson() => {
"\u0024": empty.toJson(),
"channel": channel.toJson(),
};
}
class Channel {
Channel({
required this.title,
required this.link,
required this.description,
required this.language,
required this.copyright,
required this.image,
required this.item,
});
String? title;
String? link;
String? description;
String? language;
String? copyright;
Image image;
List<Item> item;
factory Channel.fromJson(Map<String, dynamic> json) => Channel(
title: json["title"],
link: json["link"],
description: json["description"],
language: json["language"],
copyright: json["copyright"],
image: Image.fromJson(json["image"]),
item: List<Item>.from(json["item"].map((x) => Item.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"title": title,
"link": link,
"description": description,
"language": language,
"copyright": copyright,
"image": image.toJson(),
"item": List<dynamic>.from(item.map((x) => x.toJson())),
};
}
class Image {
Image({
required this.title,
required this.url,
required this.link,
required this.width,
required this.height,
});
String? title;
String? url;
String? link;
String? width;
String? height;
factory Image.fromJson(Map<String, dynamic> json) => Image(
title: json["title"],
url: json["url"],
link: json["link"],
width: json["width"],
height: json["height"],
);
Map<String, dynamic> toJson() => {
"title": title,
"url": url,
"link": link,
"width": width,
"height": height,
};
}
class Item {
Item({
required this.title,
required this.description,
required this.link,
required this.pubDate,
});
String? title;
String? description;
String? link;
String? pubDate;
factory Item.fromJson(Map<String, dynamic> json) => Item(
title: json["title"],
description: json["description"],
link: json["link"],
pubDate: json["pubDate"],
);
Map<String, dynamic> toJson() => {
"title": title,
"description": description,
"link": link,
"pubDate": pubDate,
};
}
class Empty {
Empty({
required this.version,
});
String? version;
factory Empty.fromJson(Map<String, dynamic> json) => Empty(
version: json["version"],
);
Map<String, dynamic> toJson() => {
"version": version,
};
}
This is where i call api :
import 'package:flutter/material.dart';
import 'package:halkaarzhisseler/models/apis/economy_api.dart';
import 'package:http/http.dart' as http;
import '../models/apis/economy_xml.dart';
import 'haberdetail.dart';
class Economy extends StatefulWidget {
const Economy({Key? key}) : super(key: key);
@override
State<Economy> createState() => _EconomyState();
}
class _EconomyState extends State<Economy> {
ScrollController? controller;
final scaffoldKey = GlobalKey<ScaffoldState>();
final url = Uri.parse('https://v1.nocodeapi.com/miktadtahir/xml_to_json/htvLvoPDCwIEyTxa?url=https://ekonomigundemi.com.tr/rss/ekonomi/246.xml');
var counter;
EconomylistXml? haberResult;
Future callHaber() async {
try{
final response = await http.get(url);
if(response.statusCode == 200){
var rss = economylistXmlFromJson(response.body);
if(mounted);
setState(() {
counter = haberResult?.rss.channel.item.length;
haberResult = rss;
});
return rss;
} else {
print(response.statusCode);
}
} catch(e) {
print(e.toString());
}
}
@override
void initState() {
// TODO: implement initState
super.initState();
callHaber();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: false,
automaticallyImplyLeading: false,
title: Text(
'Ekonomi Haberleri'
),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: counter != null ?
ListView.builder(
itemCount: counter,
itemBuilder: (context, index){
return Card(
child: ListTile(
title: Text(haberResult?.rss.channel.item[index].title??""),
onTap: () => Navigator.push(
context, MaterialPageRoute(builder: (context) => HaberDetailScreen( subtitle: haberResult?.rss.channel.item[index].title??"", title: haberResult?.rss.channel.item[index].description??"")),),
),
);
}) : Center(child: CircularProgressIndicator(
)),
),
),
);
}
}
/*class Economy extends StatefulWidget {
const Economy({Key? key}) : super(key: key);
@override
State<Economy> createState() => _EconomyState();
}
class _EconomyState extends State<Economy> {
ScrollController? controller;
final scaffoldKey = GlobalKey<ScaffoldState>();
final url = Uri.parse('https://api.collectapi.com/news/getNews?country=tr&tag=economy&padding=10');
var counter;
Economylist? haberResult;
Future callHaber() async {
try{
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
'Authorization': 'apikey 3fPhNZfVyrl8dOAkT86niI:3g2OzN57bil8vArOdVE3ka'
};
final response = await http.get(url,headers:requestHeaders);
if(response.statusCode == 200){
var result = economylistFromJson(response.body);
if(mounted);
setState(() {
counter = counter = result.result.length;
haberResult = result;
});
return result;
} else {
print(response.statusCode);
}
} catch(e) {
print(e.toString());
}
}
@override
void initState() {
// TODO: implement initState
super.initState();
callHaber();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: false,
automaticallyImplyLeading: false,
title: Text(
'Ekonomi Haberleri'
),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: counter != null ?
ListView.builder(
itemCount: counter,
itemBuilder: (context, index){
return Card(
child: ListTile(
title: Text(haberResult?.result[index].name??""),
leading: CircleAvatar(
backgroundImage: NetworkImage(haberResult?.result[index].image??""),),
onTap: () => Navigator.push(
context, MaterialPageRoute(builder: (context) => HaberDetailScreen( subtitle: haberResult?.result[index].description??"", title: haberResult?.result[index].name??"",image: haberResult?.result[index].image??"")),),
),
);
}) : Center(child: CircularProgressIndicator(
)),
),
),
);
}
}
*/
I see no error in the console. Only CircularProgressIndicator working. How can i fix this? Thanks for your help
CodePudding user response:
Just switch these two lines:
counter = haberResult?.rss.channel.item.length;
haberResult = rss;
to
haberResult = rss;
counter = haberResult?.rss.channel.item.length;
You are trying to access haberResult before you assign it
CodePudding user response:
Instead of calling api in initState, you should use FutureBuilder like this:
FutureBuilder(
future: callHaber(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else {
if (snapshot.hasError) {
return Text('has error');
} else {
return ListView.builder(
itemCount: counter,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(
haberResult?.rss.channel.item[index].title ??
""),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HaberDetailScreen(
subtitle: haberResult
?.rss.channel.item[index].title ??
"",
title: haberResult?.rss.channel
.item[index].description ??
"")),
),
),
);
});
}
}
},
)
CodePudding user response:
Replace callHaber()
function with this
Future callHaber() async {
try{
final response = await http.get(url);
if(response.statusCode == 200){
haberResult = economylistXmlFromJson(response.body);
if(mounted);
setState(() {
counter = haberResult?.rss.channel.item.length;
});
return haberResult;
} else {
print(response.statusCode);
}
} catch(e) {
print(e.toString());
}
}