My app doesn't recognize data from model file - flutter

Hello this is my model file;
// To parse this JSON data, do
//
// final hisselist = hisselistFromJson(jsonString);
import 'dart:convert';
Hisselist hisselistFromJson(String str) => Hisselist.fromJson(json.decode(str));
String hisselistToJson(Hisselist data) => json.encode(data.toJson());
class Hisselist {
Hisselist({
required this.success,
required this.result,
});
bool success;
List<dynamic> result;
factory Hisselist.fromJson(Map<String, dynamic> json) => Hisselist(
success: json["success"],
result: List<dynamic>.from(json["result"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"success": success,
"result": List<dynamic>.from(result.map((x) => x)),
};
}
class ResultClass {
ResultClass({
required this.rate,
required this.lastprice,
required this.lastpricestr,
required this.hacim,
required this.hacimstr,
required this.text,
required this.code,
});
double rate;
double lastprice;
String lastpricestr;
double hacim;
String hacimstr;
String text;
String code;
factory ResultClass.fromJson(Map<String, dynamic> json) => ResultClass(
rate: json["rate"].toDouble(),
lastprice: json["lastprice"].toDouble(),
lastpricestr: json["lastpricestr"],
hacim: json["hacim"].toDouble(),
hacimstr: json["hacimstr"],
text: json["text"],
code: json["code"],
);
Map<String, dynamic> toJson() => {
"rate": rate,
"lastprice": lastprice,
"lastpricestr": lastpricestr,
"hacim": hacim,
"hacimstr": hacimstr,
"text": text,
"code": code,
};
}
And this is my file where i call API
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:easy_localization/easy_localization.dart';
import '../models/apis/hisselist.dart';
class Stocks extends StatefulWidget {
Stocks({Key? key}) : super(key: key);
#override
_StocksState createState() => _StocksState();
}
class _StocksState extends State<Stocks> with AutomaticKeepAliveClientMixin {
ScrollController? controller;
final scaffoldKey = GlobalKey<ScaffoldState>();
final url = Uri.parse('https://api.collectapi.com/economy/hisseSenedi');
var counter;
var hisseResult;
Future callHisse() async {
try{
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
'Authorization': 'apikey xxx'
};
final response = await http.get(url,headers:requestHeaders);
if(response.statusCode == 200){
var result = hisselistFromJson(response.body);
if(mounted);
setState(() {
counter = 200;
hisseResult = result;
});
return result;
} else {
print(response.statusCode);
}
} catch(e) {
print(e.toString());
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
callHisse();
}
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: AppBar(
centerTitle: false,
automaticallyImplyLeading: false,
title: Text(
'Hisseler'
).tr(),
),
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(hisseResult.data[index].code),
subtitle: Text(hisseResult.data[index].text),
),
);
}) : Center(child: CircularProgressIndicator(
)),
),
),
);
}
#override
bool get wantKeepAlive => true;
}
And I'm getting this error?
What's wrong with it?
Thanks for your help

Hisselist class has only two properties, success and result.
This line of code returns result that is Hisselist type:
var result = hisselistFromJson(response.body);
You should avoid using var type here and set Hisselist instead:
Hisselist? result = hisselistFromJson(response.body);
hisseResult variable is also Hisselist type so you can only use success and result properties, there is no data property defined in Hisselist class.
Hisselist? hisseResult instead od var type.
title: Text(hisseResult?.result[index].code ?? ""),
subtitle: Text(hisseResult?.result[index].text ?? ""),

There is no field as it described on your model class
I think you want result.
Try var hisseResult; to Hisselist? hisseResult;
title: Text(hisseResult?.result[index].code??""),

hisseResult.result[index] replace for hisseResult.data[index]
itemCount: hisseResult.result.length replace for itemCount: counter,

Related

error: The operator '[]' isn't defined for the type 'Haberler'. flutter

i converted XML to api from a service:
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.haberler,
});
Haberler haberler;
factory EconomylistXml.fromJson(Map<String, dynamic> json) => EconomylistXml(
haberler: Haberler.fromJson(json["haberler"]),
);
Map<String, dynamic> toJson() => {
"haberler": haberler.toJson(),
};
}
class Haberler {
Haberler({
required this.haber,
});
List<Haber> haber;
factory Haberler.fromJson(Map<String, dynamic> json) => Haberler(
haber: List<Haber>.from(json["haber"].map((x) => Haber.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"haber": List<dynamic>.from(haber.map((x) => x.toJson())),
};
}
class Haber {
Haber({
required this.haberManset,
required this.haberResim,
required this.haberLink,
required this.haberId,
required this.haberVideo,
required this.haberAciklama,
required this.haberMetni,
required this.haberKategorisi,
required this.haberTarihi,
required this.mansetResim,
required this.izlesId,
required this.yorumSay,
required this.okunmaadedi,
required this.anasayfamanset,
required this.kategorimanset,
});
String haberManset;
String haberResim;
String haberLink;
String haberId;
String haberVideo;
String haberAciklama;
String haberMetni;
HaberKategorisi? haberKategorisi;
String haberTarihi;
String mansetResim;
String izlesId;
String yorumSay;
String okunmaadedi;
String anasayfamanset;
String kategorimanset;
factory Haber.fromJson(Map<String, dynamic> json) => Haber(
haberManset: json["haber_manset"],
haberResim: json["haber_resim"],
haberLink: json["haber_link"],
haberId: json["haber_id"],
haberVideo: json["haber_video"],
haberAciklama: json["haber_aciklama"],
haberMetni: json["haber_metni"],
haberKategorisi: haberKategorisiValues.map[json["haber_kategorisi"]],
haberTarihi: json["haber_tarihi"],
mansetResim: json["manset_resim"],
izlesId: json["izles_id"],
yorumSay: json["yorumSay"],
okunmaadedi: json["okunmaadedi"],
anasayfamanset: json["anasayfamanset"],
kategorimanset: json["kategorimanset"],
);
Map<String, dynamic> toJson() => {
"haber_manset": haberManset,
"haber_resim": haberResim,
"haber_link": haberLink,
"haber_id": haberId,
"haber_video": haberVideo,
"haber_aciklama": haberAciklama,
"haber_metni": haberMetni,
"haber_kategorisi": haberKategorisiValues.reverse[haberKategorisi],
"haber_tarihi": haberTarihi,
"manset_resim": mansetResim,
"izles_id": izlesId,
"yorumSay": yorumSay,
"okunmaadedi": okunmaadedi,
"anasayfamanset": anasayfamanset,
"kategorimanset": kategorimanset,
};
}
enum HaberKategorisi { EKONOMI, DNYA }
final haberKategorisiValues = EnumValues({
"Dünya": HaberKategorisi.DNYA,
"Ekonomi": HaberKategorisi.EKONOMI
});
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!;
}
}
And this is my file where i call api
import 'package:flutter/material.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://www.trthaber.com/xml_mobile.php?tur=xml_genel&kategori=ekonomi&adet=20&selectEx=yorumSay,okunmaadedi,anasayfamanset,kategorimanset');
var counter;
EconomylistXml? haberResult;
Future callHaber() async {
try{
final response = await http.get(url);
if(response.statusCode == 200){
var haberler = economylistXmlFromJson(response.body);
if(mounted);
setState(() {
haberResult = haberler;
});
return haberler;
} 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?.haberler[index].haberManset??""),
leading: CircleAvatar(
backgroundImage: NetworkImage(haberResult?.haberler[index].haberResim??""),),
onTap: () => Navigator.push(
context, MaterialPageRoute(builder: (context) => HaberDetailScreen( subtitle: haberResult?.haberler[index].haberMetni??"", title: haberResult?.haberler[index].haberManset??"",image: haberResult?.haberler[index].haberResim??"")),),
),
);
}) : Center(child: CircularProgressIndicator(
)),
),
),
);
}
}
I'm getting errors where i call datas from model :
error: The operator '[]' isn't defined for the type 'Haberler'.
ı get this error on these lines
child: ListTile(
title: Text(haberResult?.haberler[index].haberManset??""),
leading: CircleAvatar(
backgroundImage: NetworkImage(haberResult?.haberler[index].haberResim??""),),
onTap: () => Navigator.push(
context, MaterialPageRoute(builder: (context) => HaberDetailScreen( subtitle: haberResult?.haberler[index].haberMetni??"", title: haberResult?.haberler[index].haberManset??"",image: haberResult?.haberler[index].haberResim??"")),),
),
how can i fix this?
Thanks for your help
Add .haber after .haberler Because Haberler is not a list, Haber is a list so you can access index from haber.
child: ListTile(
title: Text(haberResult?.haberler.haber[index].haberManset??""),
leading: CircleAvatar(
backgroundImage: NetworkImage(haberResult?.haberler.haber[index].haberResim??""),),
onTap: () => Navigator.push(
context, MaterialPageRoute(builder: (context) => HaberDetailScreen( subtitle: haberResult?.haberler.haber[index].haberMetni??"", title: haberResult?.haberler.haber[index].haberManset??"",image: haberResult?.haberler.haber[index].haberResim??"")),),
),

Class '_InternalLinkedHashMap<String, dynamic>' has no instance getter 'name'. Receiver: _LinkedHashMap len:7 Tried calling: name Flutter

im trying to call an api.
This is model :
// To parse this JSON data, do
//
// final economylist = economylistFromJson(jsonString);
import 'dart:convert';
Economylist economylistFromJson(String str) => Economylist.fromJson(json.decode(str));
String economylistToJson(Economylist data) => json.encode(data.toJson());
class Economylist {
Economylist({
required this.success,
required this.result,
});
bool success;
List<dynamic> result;
factory Economylist.fromJson(Map<String, dynamic> json) => Economylist(
success: json["success"],
result: List<dynamic>.from(json["result"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"success": success,
"result": List<dynamic>.from(result.map((x) => x)),
};
}
class ResultClass {
ResultClass({
required this.key,
required this.url,
required this.description,
required this.image,
required this.name,
required this.source,
});
String key;
String url;
String description;
String image;
String name;
String source;
factory ResultClass.fromJson(Map<String, dynamic> json) => ResultClass(
key: json["key"],
url: json["url"],
description: json["description"],
image: json["image"],
name: json["name"],
source: json["source"],
);
Map<String, dynamic> toJson() => {
"key": key,
"url": url,
"description": description,
"image": image,
"name": name,
"source": source,
};
}
This is my file where i call api
import 'package:flutter/material.dart';
import 'package:halkaarzhisseler/models/apis/economy_api.dart';
import 'package:http/http.dart' as http;
class Economy extends StatefulWidget {
const Economy({Key? key}) : super(key: key);
#override
State<Economy> createState() => _EconomyState();
}
class _EconomyState extends State<Economy> {
final scaffoldKey = GlobalKey<ScaffoldState>();
final url = Uri.parse('https://api.collectapi.com/news/getNews?country=tr&tag=economy');
var counter;
Economylist? haberResult;
Future callHaber() async {
try{
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
'Authorization': 'apikey xxx'
};
final response = await http.get(url,headers:requestHeaders);
if(response.statusCode == 200){
var result = economylistFromJson(response.body);
if(mounted);
setState(() {
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(
'Hisseler'
),
),
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??""),
subtitle: Text(haberResult?.result[index].source??""), ),
);
}) : Center(child: CircularProgressIndicator(
)),
),
),
);
}
}
This is the error i get :
I think im making some mistake when im calling the api about Future but i couldnt fix it. How can i fix this?
thanks for your help
You need to change result property of Economylist class to List. use this model class:
class Economylist {
Economylist({
required this.success,
required this.result,
});
bool success;
List<ResultClass> result;
factory Economylist.fromJson(Map<String, dynamic> json) => Economylist(
success: json["success"],
result: json["result"].map<ResultClass>((x) => ResultClass.fromJson(x)).toList(),
);
Map<String, dynamic> toJson() => {
"success": success,
"result": result.map((x) => x.toJson()),
};
}

type 'Null' is not a subtype of type 'String' flutter on api call

Im using a service to create api from xml. This is my model file:
// 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.haberler,
});
Haberler haberler;
factory EconomylistXml.fromJson(Map<String, dynamic> json) => EconomylistXml(
haberler: Haberler.fromJson(json["haberler"]),
);
Map<String, dynamic> toJson() => {
"haberler": haberler.toJson(),
};
}
class Haberler {
Haberler({
required this.haber,
});
List<Haber> haber;
factory Haberler.fromJson(Map<String, dynamic> json) => Haberler(
haber: List<Haber>.from(json["haber"].map((x) => Haber.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"haber": List<dynamic>.from(haber.map((x) => x.toJson())),
};
}
class Haber {
Haber({
required this.haberManset,
required this.haberResim,
required this.haberLink,
required this.haberId,
required this.haberVideo,
required this.haberAciklama,
required this.haberMetni,
required this.haberKategorisi,
required this.haberTarihi,
required this.mansetResim,
required this.izlesId,
required this.yorumSay,
required this.okunmaadedi,
required this.anasayfamanset,
required this.kategorimanset,
});
String haberManset;
String haberResim;
String haberLink;
String haberId;
String haberVideo;
String haberAciklama;
String haberMetni;
HaberKategorisi? haberKategorisi;
String haberTarihi;
String mansetResim;
String izlesId;
String yorumSay;
String okunmaadedi;
String anasayfamanset;
String kategorimanset;
factory Haber.fromJson(Map<String, dynamic> json) => Haber(
haberManset: json["haber_manset"],
haberResim: json["haber_resim"],
haberLink: json["haber_link"],
haberId: json["haber_id"],
haberVideo: json["haber_video"],
haberAciklama: json["haber_aciklama"],
haberMetni: json["haber_metni"],
haberKategorisi: haberKategorisiValues.map[json["haber_kategorisi"]],
haberTarihi: json["haber_tarihi"],
mansetResim: json["manset_resim"],
izlesId: json["izles_id"],
yorumSay: json["yorumSay"],
okunmaadedi: json["okunmaadedi"],
anasayfamanset: json["anasayfamanset"],
kategorimanset: json["kategorimanset"],
);
Map<String, dynamic> toJson() => {
"haber_manset": haberManset,
"haber_resim": haberResim,
"haber_link": haberLink,
"haber_id": haberId,
"haber_video": haberVideo,
"haber_aciklama": haberAciklama,
"haber_metni": haberMetni,
"haber_kategorisi": haberKategorisiValues.reverse[haberKategorisi],
"haber_tarihi": haberTarihi,
"manset_resim": mansetResim,
"izles_id": izlesId,
"yorumSay": yorumSay,
"okunmaadedi": okunmaadedi,
"anasayfamanset": anasayfamanset,
"kategorimanset": kategorimanset,
};
}
enum HaberKategorisi { EKONOMI, DNYA }
final haberKategorisiValues = EnumValues({
"Dünya": HaberKategorisi.DNYA,
"Ekonomi": HaberKategorisi.EKONOMI
});
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!;
}
}
and this is file 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://www.trthaber.com/xml_mobile.php?tur=xml_genel&kategori=ekonomi&adet=20&selectEx=yorumSay,okunmaadedi,anasayfamanset,kategorimanset');
var counter;
EconomylistXml? haberResult;
Future callHaber() async {
try{
final response = await http.get(url);
if(response.statusCode == 200){
var haberler = economylistXmlFromJson(response.body);
if(mounted);
setState(() {
haberResult = haberler;
});
return haberler;
} 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?.haberler.haber[index].haberManset??""),
leading: CircleAvatar(
backgroundImage: NetworkImage(haberResult?.haberler.haber[index].haberResim??""),),
onTap: () => Navigator.push(
context, MaterialPageRoute(builder: (context) => HaberDetailScreen( subtitle: haberResult?.haberler.haber[index].haberMetni??"", title: haberResult?.haberler.haber[index].haberManset??"",image: haberResult?.haberler.haber[index].haberResim??"")),),
),
);
}) : 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'm getting this error on console : type 'Null' is not a subtype of type 'String' and CircularProgressIndicator working continuously. How can i fix this?
Thanks for your help
The handle null value it is better to make variable nullable data on entities
class Haber {
String? haberManset;
String? haberResim;
String? haberLink;
Or provide empty string on null case while reading JSON
haberVideo: json["haber_video"]??"", //this
izlesId: json["izles_id"]??"",
You can make response != null to the top. And check the debug console for the response. Probably you get some other exception like socket exception.
try{
final response = await http.get(url);
if(response != null){ //this line you need to add
if(response.statusCode == 200){
var haberler = economylistXmlFromJson(response.body);
if(mounted);
setState(() {
haberResult = haberler;
});
return haberler;
} else {
print(response.statusCode);
}
}else{
//stop indicator in here if response is null
//you're code in here
}
} catch(e) {
print(e.toString());
}
I hope this helps
Change String to String? at not required fields:
class Haber {
Haber({
required this.haberManset,
required this.haberResim,
required this.haberLink,
required this.haberId,
required this.haberVideo,
required this.haberAciklama,
required this.haberMetni,
required this.haberKategorisi,
required this.haberTarihi,
required this.mansetResim,
required this.izlesId,
required this.yorumSay,
required this.okunmaadedi,
required this.anasayfamanset,
required this.kategorimanset,
});
String haberManset;
String haberResim;
String haberLink;
String haberId;
String? haberVideo; //<-- here
String haberAciklama;
String haberMetni;
HaberKategorisi? haberKategorisi;
String haberTarihi;
String mansetResim;
String? izlesId; //<-- and here
String yorumSay;
String okunmaadedi;
String anasayfamanset;
String kategorimanset;
factory Haber.fromJson(Map<String, dynamic> json) => Haber(
haberManset: json["haber_manset"],
haberResim: json["haber_resim"],
haberLink: json["haber_link"],
haberId: json["haber_id"],
haberVideo: json["haber_video"],
haberAciklama: json["haber_aciklama"],
haberMetni: json["haber_metni"],
haberKategorisi: haberKategorisiValues.map[json["haber_kategorisi"]],
haberTarihi: json["haber_tarihi"],
mansetResim: json["manset_resim"],
izlesId: json["izles_id"],
yorumSay: json["yorumSay"],
okunmaadedi: json["okunmaadedi"],
anasayfamanset: json["anasayfamanset"],
kategorimanset: json["kategorimanset"],
);
Map<String, dynamic> toJson() => {
"haber_manset": haberManset,
"haber_resim": haberResim,
"haber_link": haberLink,
"haber_id": haberId,
"haber_video": haberVideo,
"haber_aciklama": haberAciklama,
"haber_metni": haberMetni,
"haber_kategorisi": haberKategorisiValues.reverse[haberKategorisi],
"haber_tarihi": haberTarihi,
"manset_resim": mansetResim,
"izles_id": izlesId,
"yorumSay": yorumSay,
"okunmaadedi": okunmaadedi,
"anasayfamanset": anasayfamanset,
"kategorimanset": kategorimanset,
};
}
Try this
class Haber {
String haberManset = "";
String haberResim = "";
String haberLink = ""
or
haberVideo: json["haber_video"].toString(),
izlesId: json["izles_id"].toString(),

type 'String' is not a subtype of type 'double' in type cast flutter

I'M trying to call an api. This is my model file:
// To parse this JSON data, do
//
// final hisselist = hisselistFromJson(jsonString);
import 'dart:convert';
Hisselist hisselistFromJson(String str) => Hisselist.fromJson(json.decode(str));
String hisselistToJson(Hisselist data) => json.encode(data.toJson());
class Hisselist {
Hisselist({
required this.success,
required this.result,
});
bool success;
List<ResultClass> result;
factory Hisselist.fromJson(Map<String, dynamic> json) => Hisselist(
success: json["success"],
result: List<dynamic>.from(json["result"])
.map((i) => ResultClass.fromJson(i))
.toList()
);
Map<String, dynamic> toJson() => {
"success": success,
"result": result.map((item) => item.toJson()).toList(),
};
}
class ResultClass {
ResultClass({
required this.rate,
required this.lastprice,
required this.lastpricestr,
required this.hacim,
required this.hacimstr,
required this.text,
required this.code,
});
double rate;
double lastprice;
String lastpricestr;
double hacim;
String hacimstr;
String text;
String code;
factory ResultClass.fromJson(Map<String, dynamic> json) => ResultClass(
rate: json["rate"] as double,
lastprice: json["lastprice"] as double,
lastpricestr: json["lastpricestr"],
hacim: json["hacim"] as double,
hacimstr: json["hacimstr"],
text: json["text"],
code: json["code"],
);
Map<String, dynamic> toJson() => {
"rate": rate,
"lastprice": lastprice,
"lastpricestr": lastpricestr,
"hacim": hacim,
"hacimstr": hacimstr,
"text": text,
"code": code,
};
}
This is where I call the API :
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../models/apis/hisselist.dart';
class Stocks extends StatefulWidget {
Stocks({Key? key}) : super(key: key);
#override
_StocksState createState() => _StocksState();
}
class _StocksState extends State<Stocks> with AutomaticKeepAliveClientMixin {
ScrollController? controller;
final scaffoldKey = GlobalKey<ScaffoldState>();
final url = Uri.parse('https://api.collectapi.com/economy/hisseSenedi');
var counter;
Hisselist? hisseResult;
Future callHisse() async {
try{
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
'Authorization': 'apikey xxx'
};
final response = await http.get(url,headers:requestHeaders);
if(response.statusCode == 200){
var result = hisselistFromJson(response.body);
if(mounted);
setState(() {
counter = result.result.length;
hisseResult = result;
});
return result;
} else {
print(response.statusCode);
}
} catch(e) {
print(e.toString());
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
callHisse();
}
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: AppBar(
centerTitle: false,
automaticallyImplyLeading: false,
title: Text(
'Hisseler'
),
),
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(hisseResult?.result[index].code??""),
subtitle: Text(hisseResult?.result[index].code??""), ),
);
}) : Center(child: CircularProgressIndicator(
)),
),
),
);
}
#override
bool get wantKeepAlive => true;
}
I' getting this on console and API not showing : type 'String' is not a subtype of type 'double' in type cast
How can I fix this? Thanks for your help
How can I fix this?
It is better to use .tryParse instead of forcing with as prefix. Try this for non string value
lastprice: double.tryParse(json["lastprice"]) ?? 0.0,
factory ResultClass.fromJson(Map<String, dynamic> json) => ResultClass(
rate: double.tryParse(json["rate"]) ?? 0.0,
lastprice: double.tryParse(json["lastprice"]) ?? 0.0,
lastpricestr: json["lastpricestr"],
hacim: double.tryParse(json["hacim"]) ?? 0.0,
hacimstr: json["hacimstr"],
text: json["text"],
code: json["code"],
);
Try this and when ever you like to use any double as string use .toString()
class ResultClass {
final double rate;
final double lastprice;
final String lastpricestr;
final double hacim;
final String hacimstr;
final String text;
final String code;
ResultClass({
required this.rate,
required this.lastprice,
required this.lastpricestr,
required this.hacim,
required this.hacimstr,
required this.text,
required this.code,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
result.addAll({'rate': rate});
result.addAll({'lastprice': lastprice});
result.addAll({'lastpricestr': lastpricestr});
result.addAll({'hacim': hacim});
result.addAll({'hacimstr': hacimstr});
result.addAll({'text': text});
result.addAll({'code': code});
return result;
}
factory ResultClass.fromMap(Map<String, dynamic> map) {
return ResultClass(
rate: map['rate']?.toDouble() ?? 0.0,
lastprice: map['lastprice']?.toDouble() ?? 0.0,
lastpricestr: map['lastpricestr'] ?? '',
hacim: map['hacim']?.toDouble() ?? 0.0,
hacimstr: map['hacimstr'] ?? '',
text: map['text'] ?? '',
code: map['code'] ?? '',
);
}
String toJson() => json.encode(toMap());
factory ResultClass.fromJson(String source) =>
ResultClass.fromMap(json.decode(source));
}

cannot access JSON datas

I cannot access categories.id and name. But code should be work. Unfortunately I cannot find the reason.
here is category.view:
import 'package:flutter/material.dart';
import '/data/models/models.dart';
import '/data/services/services.dart';
import '/data/models/category.dart';
class CategoryViewDetail extends StatefulWidget {
const CategoryViewDetail({Key? key}) : super(key: key);
#override
_CategoryViewDetailState createState() => _CategoryViewDetailState();
}
class _CategoryViewDetailState extends State<CategoryViewDetail> {
final _categoryService = NewsService();
late Future<Categories> _futureCategories;
#override
void initState() {
_futureCategories = _categoryService.getAllCategories();
super.initState();
}
...
...
...
...
child: FutureBuilder<Categories>(
future: _futureCategories,
builder: (BuildContext context, AsyncSnapshot<Categories> snapshot) {
if (snapshot.hasData) {
final categories = snapshot.data?.data;
return Card(
elevation: 4.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: ListTile(
title: Text(
'Title: ${categories?.name}',
),
subtitle: Text(
'Content: ${categories?.id}',
),
),
);
news_service.dart
Future<Categories> getAllCategories() async {
final _queryParametersCategoryId = {
"route": "services/news/getAllCategories",
};
///
final _url = Uri.https(
_authority,
_unencodedPath,
_queryParametersCategoryId,
);
///
final _headers = <String, String>{
'content-type': 'application/json',
};
///
final _response = await http.get(
_url,
headers: _headers,
);
/// JSON Object To String
final _jsonBody = _response.body;
/// String To Map
final Map<String, dynamic> _decodedBody = jsonDecode(_jsonBody);
/// JSON (Map) To Dart (Object)
final _articleIdResponse = Categories.fromJson(_decodedBody);
switch (_response.statusCode) {
case 200:
/// Response: Dart Object
return _articleIdResponse;
and finally category.dart
class Categories {
const Categories({
this.success,
this.message,
this.errorCode,
this.data,
});
final bool? success;
final String? message;
final int? errorCode;
final List<Category>? data;
factory Categories.fromJson(Map<String, dynamic> json) => Categories(
success: json["success"],
message: json["message"],
errorCode: json["error_code"],
data:
List<Category>.from(json["data"].map((x) => Category.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"success": success,
"message": message,
"error_code": errorCode,
"data": List<dynamic>.from(data!.map((x) => x.toJson())),
};
}
class Category {
const Category({
this.id,
this.name,
});
final String? id;
final String? name;
factory Category.fromJson(Map<String, dynamic> json) => Category(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
I am newbie and more than one week I am trying many things to do fix it but unfortunately I could not find the problem. The section of my apps news, images, an all other stuff works but I cannot get categories.
Any help?
final categories = snapshot.data?.data;
You have defined the parameter data as a List<Category> inside the Categories class.
That's why you can't access to name or id parameters doing categories.name.
You need first to access to a certain position like categories[0].name.
I suggest you to return a ListView.builder from the FutureBuilder.