Flutter Json Map<String, double> Listview - json
Hello i want to show Json data on listview.builder. I can take a values from the Json but i cant show them on the listview.
This is the Json data.
{"success":true,"timestamp":1578778505,"base":"EUR","date":"2020-01-11","rates":{"AED":4.084603,"AFN":86.369994,"ALL":122.079994,"AMD":531.079988,"ANG":1.8526,"AOA":538.513234,
"ARS":66.270498,...}}
I want to show "rates" values on Listview.
There is a model for Json.(I used to model for quicktype.io)
Currency currencyFromJson(String str) => Currency.fromJson(json.decode(str));
String currencyToJson(Currency data) => json.encode(data.toJson());
class Currency {
bool success;
int timestamp;
String base;
DateTime date;
Map<String, double> rates;
Currency({
this.success,
this.timestamp,
this.base,
this.date,
this.rates,
});
factory Currency.fromJson(Map<String, dynamic> json) => Currency(
success: json["success"],
timestamp: json["timestamp"],
base: json["base"],
date: DateTime.parse(json["date"]),
rates: Map.from(json["rates"]).map((k, v) => MapEntry<String, double>(k, v.toDouble())),
);
Map<String, dynamic> toJson() => {
"success": success,
"timestamp": timestamp,
"base": base,
"date": "${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}",
"rates": Map.from(rates).map((k, v) => MapEntry<String, dynamic>(k, v)),
};
}
..
class _CurrencyListState extends State<CurrencyList> {
Map<String, double> rates;
String url= "xxxx";
Currency currency;
Future takeCurrency() async{
var response = await http.get(url);
var decodedJson = json.decode(response.body);
currency = Currency.fromJson(decodedJson);
rates = Map.from(decodedJson["rates"]).map((key, value) => MapEntry<String, double>(key, value));
}
void initState() {
// TODO: implement initState
super.initState();
takeCurrency();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Currency"),),
body: FutureBuilder(future: takeCurrency() ,builder: (BuildContext context, AsyncSnapshot takenCurrency){
print('takenCurrency data is: ${currency.rates}');
return ListView.builder(itemCount: currency.rates.length ,itemBuilder: (context, index){
return Card(
child: ListTile(
title: Text(
I tried to print values on there but i couldnt find a way.
Thanks.
You are trying to print values but you can't? This is because your Future is not returning anything, so the FutureBuilder's snapshot is void.
(This is why it's important to give a type parameter to Future, such as Future<Currency>: the compiler would've caught you were not returning a Currency.)
Since you are using a StatefulWidget I assume you want to cache the result of your future, correct?
This is how:
class _CurrencyListState extends State<CurrencyList> {
Map<String, double> rates;
String url= "xxxx";
Future<Currency> future;
Future<Currency> takeCurrency() async{
var response = await http.get(url);
var decodedJson = json.decode(response.body);
return Currency.fromJson(decodedJson);
}
void initState() {
// TODO: implement initState
super.initState();
future = takeCurrency();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Currency"),),
body: FutureBuilder(future: future ,builder: (BuildContext context, AsyncSnapshot snapshot){
if (snapshot.hasData) {
final currency = snapshot.data;
print('takenCurrency data is: ${currency.rates}');
return ListView.builder(itemCount: currency.rates.length ,itemBuilder: (context, index){
return Card(
child: ListTile(
title: Text(
When the future completes, now the snapshot will have data.
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:json_parsing/models.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Data> dataList = List();
bool _isLoading = false;
Rates rates = Rates();
Future<String> loadPersonFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
Future loadyourData() async {
setState(() {
_isLoading = true;
});
// this is the local json that i have loaded from the assets folder
// you can make the http call here and else everything later is the same.
String jsonString = await loadPersonFromAssets();
final dataRates = dataFromJson(jsonString);
dataList.add(dataRates);
setState(() {
_isLoading = false;
});
}
#override
void initState() {
// TODO: implement initState
super.initState();
loadyourData();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: _isLoading
? CircularProgressIndicator()
: new ListView.builder(
itemCount: dataList.length,
itemBuilder: (BuildContext ctxt, int index) {
return Card(
child: Column(
children: <Widget>[
new Text(dataList[index].rates.tRY.toString()),
new Text(dataList[index].rates.uAH.toString()),
new Text(dataList[index].rates.wST.toString()),
new Text(dataList[index].rates.zMW.toString()),
],
),
);
}),
),
);
}
}
This is the main file where the data gets loaded and its been shown in the list view.
import 'dart:convert';
//// final data = dataFromJson(jsonString);
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
bool success;
int timestamp;
String base;
String date;
Rates rates;
Data({this.success, this.timestamp, this.base, this.date, this.rates});
Data.fromJson(Map<String, dynamic> json) {
success = json['success'];
timestamp = json['timestamp'];
base = json['base'];
date = json['date'];
rates = json['rates'] != null ? new Rates.fromJson(json['rates']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['success'] = this.success;
data['timestamp'] = this.timestamp;
data['base'] = this.base;
data['date'] = this.date;
if (this.rates != null) {
data['rates'] = this.rates.toJson();
}
return data;
}
}
class Rates {
double aED;
double aFN;
double aLL;
double aMD;
double aNG;
double aOA;
double aRS;
double aUD;
double aWG;
double aZN;
double bAM;
double bBD;
double bDT;
double bGN;
double bHD;
double bIF;
double bMD;
double bND;
double bOB;
double bRL;
double bSD;
double bTC;
double bTN;
double bWP;
double bYN;
double bYR;
double bZD;
double cAD;
double cDF;
double cHF;
double cLF;
double cLP;
double cNY;
double cOP;
double cRC;
double cUC;
double cUP;
double cVE;
double cZK;
double dJF;
double dKK;
double dOP;
double dZD;
double eGP;
double eRN;
double eTB;
int eUR;
double fJD;
double fKP;
double gBP;
double gEL;
double gGP;
double gHS;
double gIP;
double gMD;
double gNF;
double gTQ;
double gYD;
double hKD;
double hNL;
double hRK;
double hTG;
double hUF;
double iDR;
double iLS;
double iMP;
double iNR;
double iQD;
double iRR;
double iSK;
double jEP;
double jMD;
double jOD;
double jPY;
double kES;
double kGS;
double kHR;
double kMF;
double kPW;
double kRW;
double kWD;
double kYD;
double kZT;
double lAK;
double lBP;
double lKR;
double lRD;
double lSL;
double lTL;
double lVL;
double lYD;
double mAD;
double mDL;
double mGA;
double mKD;
double mMK;
double mNT;
double mOP;
double mRO;
double mUR;
double mVR;
double mWK;
double mXN;
double mYR;
double mZN;
double nAD;
double nGN;
double nIO;
double nOK;
double nPR;
double nZD;
double oMR;
double pAB;
double pEN;
double pGK;
double pHP;
double pKR;
double pLN;
double pYG;
double qAR;
double rON;
double rSD;
double rUB;
double rWF;
double sAR;
double sBD;
double sCR;
double sDG;
double sEK;
double sGD;
double sHP;
double sLL;
double sOS;
double sRD;
double sTD;
double sVC;
double sYP;
double sZL;
double tHB;
double tJS;
double tMT;
double tND;
double tOP;
double tRY;
double tTD;
double tWD;
double tZS;
double uAH;
double uGX;
double uSD;
double uYU;
double uZS;
double vEF;
double vND;
double vUV;
double wST;
double xAF;
double xAG;
double xAU;
double xCD;
double xDR;
double xOF;
double xPF;
double yER;
double zAR;
double zMK;
double zMW;
double zWL;
Rates(
{this.aED,
this.aFN,
this.aLL,
this.aMD,
this.aNG,
this.aOA,
this.aRS,
this.aUD,
this.aWG,
this.aZN,
this.bAM,
this.bBD,
this.bDT,
this.bGN,
this.bHD,
this.bIF,
this.bMD,
this.bND,
this.bOB,
this.bRL,
this.bSD,
this.bTC,
this.bTN,
this.bWP,
this.bYN,
this.bYR,
this.bZD,
this.cAD,
this.cDF,
this.cHF,
this.cLF,
this.cLP,
this.cNY,
this.cOP,
this.cRC,
this.cUC,
this.cUP,
this.cVE,
this.cZK,
this.dJF,
this.dKK,
this.dOP,
this.dZD,
this.eGP,
this.eRN,
this.eTB,
this.eUR,
this.fJD,
this.fKP,
this.gBP,
this.gEL,
this.gGP,
this.gHS,
this.gIP,
this.gMD,
this.gNF,
this.gTQ,
this.gYD,
this.hKD,
this.hNL,
this.hRK,
this.hTG,
this.hUF,
this.iDR,
this.iLS,
this.iMP,
this.iNR,
this.iQD,
this.iRR,
this.iSK,
this.jEP,
this.jMD,
this.jOD,
this.jPY,
this.kES,
this.kGS,
this.kHR,
this.kMF,
this.kPW,
this.kRW,
this.kWD,
this.kYD,
this.kZT,
this.lAK,
this.lBP,
this.lKR,
this.lRD,
this.lSL,
this.lTL,
this.lVL,
this.lYD,
this.mAD,
this.mDL,
this.mGA,
this.mKD,
this.mMK,
this.mNT,
this.mOP,
this.mRO,
this.mUR,
this.mVR,
this.mWK,
this.mXN,
this.mYR,
this.mZN,
this.nAD,
this.nGN,
this.nIO,
this.nOK,
this.nPR,
this.nZD,
this.oMR,
this.pAB,
this.pEN,
this.pGK,
this.pHP,
this.pKR,
this.pLN,
this.pYG,
this.qAR,
this.rON,
this.rSD,
this.rUB,
this.rWF,
this.sAR,
this.sBD,
this.sCR,
this.sDG,
this.sEK,
this.sGD,
this.sHP,
this.sLL,
this.sOS,
this.sRD,
this.sTD,
this.sVC,
this.sYP,
this.sZL,
this.tHB,
this.tJS,
this.tMT,
this.tND,
this.tOP,
this.tRY,
this.tTD,
this.tWD,
this.tZS,
this.uAH,
this.uGX,
this.uSD,
this.uYU,
this.uZS,
this.vEF,
this.vND,
this.vUV,
this.wST,
this.xAF,
this.xAG,
this.xAU,
this.xCD,
this.xDR,
this.xOF,
this.xPF,
this.yER,
this.zAR,
this.zMK,
this.zMW,
this.zWL});
Rates.fromJson(Map<String, dynamic> json) {
aED = json['AED'];
aFN = json['AFN'];
aLL = json['ALL'];
aMD = json['AMD'];
aNG = json['ANG'];
aOA = json['AOA'];
aRS = json['ARS'];
aUD = json['AUD'];
aWG = json['AWG'];
aZN = json['AZN'];
bAM = json['BAM'];
bBD = json['BBD'];
bDT = json['BDT'];
bGN = json['BGN'];
bHD = json['BHD'];
bIF = json['BIF'];
bMD = json['BMD'];
bND = json['BND'];
bOB = json['BOB'];
bRL = json['BRL'];
bSD = json['BSD'];
bTC = json['BTC'];
bTN = json['BTN'];
bWP = json['BWP'];
bYN = json['BYN'];
bYR = json['BYR'];
bZD = json['BZD'];
cAD = json['CAD'];
cDF = json['CDF'];
cHF = json['CHF'];
cLF = json['CLF'];
cLP = json['CLP'];
cNY = json['CNY'];
cOP = json['COP'];
cRC = json['CRC'];
cUC = json['CUC'];
cUP = json['CUP'];
cVE = json['CVE'];
cZK = json['CZK'];
dJF = json['DJF'];
dKK = json['DKK'];
dOP = json['DOP'];
dZD = json['DZD'];
eGP = json['EGP'];
eRN = json['ERN'];
eTB = json['ETB'];
eUR = json['EUR'];
fJD = json['FJD'];
fKP = json['FKP'];
gBP = json['GBP'];
gEL = json['GEL'];
gGP = json['GGP'];
gHS = json['GHS'];
gIP = json['GIP'];
gMD = json['GMD'];
gNF = json['GNF'];
gTQ = json['GTQ'];
gYD = json['GYD'];
hKD = json['HKD'];
hNL = json['HNL'];
hRK = json['HRK'];
hTG = json['HTG'];
hUF = json['HUF'];
iDR = json['IDR'];
iLS = json['ILS'];
iMP = json['IMP'];
iNR = json['INR'];
iQD = json['IQD'];
iRR = json['IRR'];
iSK = json['ISK'];
jEP = json['JEP'];
jMD = json['JMD'];
jOD = json['JOD'];
jPY = json['JPY'];
kES = json['KES'];
kGS = json['KGS'];
kHR = json['KHR'];
kMF = json['KMF'];
kPW = json['KPW'];
kRW = json['KRW'];
kWD = json['KWD'];
kYD = json['KYD'];
kZT = json['KZT'];
lAK = json['LAK'];
lBP = json['LBP'];
lKR = json['LKR'];
lRD = json['LRD'];
lSL = json['LSL'];
lTL = json['LTL'];
lVL = json['LVL'];
lYD = json['LYD'];
mAD = json['MAD'];
mDL = json['MDL'];
mGA = json['MGA'];
mKD = json['MKD'];
mMK = json['MMK'];
mNT = json['MNT'];
mOP = json['MOP'];
mRO = json['MRO'];
mUR = json['MUR'];
mVR = json['MVR'];
mWK = json['MWK'];
mXN = json['MXN'];
mYR = json['MYR'];
mZN = json['MZN'];
nAD = json['NAD'];
nGN = json['NGN'];
nIO = json['NIO'];
nOK = json['NOK'];
nPR = json['NPR'];
nZD = json['NZD'];
oMR = json['OMR'];
pAB = json['PAB'];
pEN = json['PEN'];
pGK = json['PGK'];
pHP = json['PHP'];
pKR = json['PKR'];
pLN = json['PLN'];
pYG = json['PYG'];
qAR = json['QAR'];
rON = json['RON'];
rSD = json['RSD'];
rUB = json['RUB'];
rWF = json['RWF'];
sAR = json['SAR'];
sBD = json['SBD'];
sCR = json['SCR'];
sDG = json['SDG'];
sEK = json['SEK'];
sGD = json['SGD'];
sHP = json['SHP'];
sLL = json['SLL'];
sOS = json['SOS'];
sRD = json['SRD'];
sTD = json['STD'];
sVC = json['SVC'];
sYP = json['SYP'];
sZL = json['SZL'];
tHB = json['THB'];
tJS = json['TJS'];
tMT = json['TMT'];
tND = json['TND'];
tOP = json['TOP'];
tRY = json['TRY'];
tTD = json['TTD'];
tWD = json['TWD'];
tZS = json['TZS'];
uAH = json['UAH'];
uGX = json['UGX'];
uSD = json['USD'];
uYU = json['UYU'];
uZS = json['UZS'];
vEF = json['VEF'];
vND = json['VND'];
vUV = json['VUV'];
wST = json['WST'];
xAF = json['XAF'];
xAG = json['XAG'];
xAU = json['XAU'];
xCD = json['XCD'];
xDR = json['XDR'];
xOF = json['XOF'];
xPF = json['XPF'];
yER = json['YER'];
zAR = json['ZAR'];
zMK = json['ZMK'];
zMW = json['ZMW'];
zWL = json['ZWL'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['AED'] = this.aED;
data['AFN'] = this.aFN;
data['ALL'] = this.aLL;
data['AMD'] = this.aMD;
data['ANG'] = this.aNG;
data['AOA'] = this.aOA;
data['ARS'] = this.aRS;
data['AUD'] = this.aUD;
data['AWG'] = this.aWG;
data['AZN'] = this.aZN;
data['BAM'] = this.bAM;
data['BBD'] = this.bBD;
data['BDT'] = this.bDT;
data['BGN'] = this.bGN;
data['BHD'] = this.bHD;
data['BIF'] = this.bIF;
data['BMD'] = this.bMD;
data['BND'] = this.bND;
data['BOB'] = this.bOB;
data['BRL'] = this.bRL;
data['BSD'] = this.bSD;
data['BTC'] = this.bTC;
data['BTN'] = this.bTN;
data['BWP'] = this.bWP;
data['BYN'] = this.bYN;
data['BYR'] = this.bYR;
data['BZD'] = this.bZD;
data['CAD'] = this.cAD;
data['CDF'] = this.cDF;
data['CHF'] = this.cHF;
data['CLF'] = this.cLF;
data['CLP'] = this.cLP;
data['CNY'] = this.cNY;
data['COP'] = this.cOP;
data['CRC'] = this.cRC;
data['CUC'] = this.cUC;
data['CUP'] = this.cUP;
data['CVE'] = this.cVE;
data['CZK'] = this.cZK;
data['DJF'] = this.dJF;
data['DKK'] = this.dKK;
data['DOP'] = this.dOP;
data['DZD'] = this.dZD;
data['EGP'] = this.eGP;
data['ERN'] = this.eRN;
data['ETB'] = this.eTB;
data['EUR'] = this.eUR;
data['FJD'] = this.fJD;
data['FKP'] = this.fKP;
data['GBP'] = this.gBP;
data['GEL'] = this.gEL;
data['GGP'] = this.gGP;
data['GHS'] = this.gHS;
data['GIP'] = this.gIP;
data['GMD'] = this.gMD;
data['GNF'] = this.gNF;
data['GTQ'] = this.gTQ;
data['GYD'] = this.gYD;
data['HKD'] = this.hKD;
data['HNL'] = this.hNL;
data['HRK'] = this.hRK;
data['HTG'] = this.hTG;
data['HUF'] = this.hUF;
data['IDR'] = this.iDR;
data['ILS'] = this.iLS;
data['IMP'] = this.iMP;
data['INR'] = this.iNR;
data['IQD'] = this.iQD;
data['IRR'] = this.iRR;
data['ISK'] = this.iSK;
data['JEP'] = this.jEP;
data['JMD'] = this.jMD;
data['JOD'] = this.jOD;
data['JPY'] = this.jPY;
data['KES'] = this.kES;
data['KGS'] = this.kGS;
data['KHR'] = this.kHR;
data['KMF'] = this.kMF;
data['KPW'] = this.kPW;
data['KRW'] = this.kRW;
data['KWD'] = this.kWD;
data['KYD'] = this.kYD;
data['KZT'] = this.kZT;
data['LAK'] = this.lAK;
data['LBP'] = this.lBP;
data['LKR'] = this.lKR;
data['LRD'] = this.lRD;
data['LSL'] = this.lSL;
data['LTL'] = this.lTL;
data['LVL'] = this.lVL;
data['LYD'] = this.lYD;
data['MAD'] = this.mAD;
data['MDL'] = this.mDL;
data['MGA'] = this.mGA;
data['MKD'] = this.mKD;
data['MMK'] = this.mMK;
data['MNT'] = this.mNT;
data['MOP'] = this.mOP;
data['MRO'] = this.mRO;
data['MUR'] = this.mUR;
data['MVR'] = this.mVR;
data['MWK'] = this.mWK;
data['MXN'] = this.mXN;
data['MYR'] = this.mYR;
data['MZN'] = this.mZN;
data['NAD'] = this.nAD;
data['NGN'] = this.nGN;
data['NIO'] = this.nIO;
data['NOK'] = this.nOK;
data['NPR'] = this.nPR;
data['NZD'] = this.nZD;
data['OMR'] = this.oMR;
data['PAB'] = this.pAB;
data['PEN'] = this.pEN;
data['PGK'] = this.pGK;
data['PHP'] = this.pHP;
data['PKR'] = this.pKR;
data['PLN'] = this.pLN;
data['PYG'] = this.pYG;
data['QAR'] = this.qAR;
data['RON'] = this.rON;
data['RSD'] = this.rSD;
data['RUB'] = this.rUB;
data['RWF'] = this.rWF;
data['SAR'] = this.sAR;
data['SBD'] = this.sBD;
data['SCR'] = this.sCR;
data['SDG'] = this.sDG;
data['SEK'] = this.sEK;
data['SGD'] = this.sGD;
data['SHP'] = this.sHP;
data['SLL'] = this.sLL;
data['SOS'] = this.sOS;
data['SRD'] = this.sRD;
data['STD'] = this.sTD;
data['SVC'] = this.sVC;
data['SYP'] = this.sYP;
data['SZL'] = this.sZL;
data['THB'] = this.tHB;
data['TJS'] = this.tJS;
data['TMT'] = this.tMT;
data['TND'] = this.tND;
data['TOP'] = this.tOP;
data['TRY'] = this.tRY;
data['TTD'] = this.tTD;
data['TWD'] = this.tWD;
data['TZS'] = this.tZS;
data['UAH'] = this.uAH;
data['UGX'] = this.uGX;
data['USD'] = this.uSD;
data['UYU'] = this.uYU;
data['UZS'] = this.uZS;
data['VEF'] = this.vEF;
data['VND'] = this.vND;
data['VUV'] = this.vUV;
data['WST'] = this.wST;
data['XAF'] = this.xAF;
data['XAG'] = this.xAG;
data['XAU'] = this.xAU;
data['XCD'] = this.xCD;
data['XDR'] = this.xDR;
data['XOF'] = this.xOF;
data['XPF'] = this.xPF;
data['YER'] = this.yER;
data['ZAR'] = this.zAR;
data['ZMK'] = this.zMK;
data['ZMW'] = this.zMW;
data['ZWL'] = this.zWL;
return data;
}
}
This is the model class as you described being generated using the QuickType.io
{
"success": true,
"timestamp": 1579491366,
"base": "EUR",
"date": "2020-01-20",
"rates": {
"AED": 4.076715,
"AFN": 85.483484,
"ALL": 122.193571,
"AMD": 533.250113,
"ANG": 1.861912,
"AOA": 543.149165,
"ARS": 66.554012,
"AUD": 1.612575,
"AWG": 1.997739,
"AZN": 1.891541,
"BAM": 1.956271,
"BBD": 2.244417,
"BDT": 94.256534,
"BGN": 1.95712,
"BHD": 0.418215,
"BIF": 2091.50477,
"BMD": 1.109855,
"BND": 1.496611,
"BOB": 7.686131,
"BRL": 4.617881,
"BSD": 1.111605,
"BTC": 0.000128,
"BTN": 78.853356,
"BWP": 11.933279,
"BYN": 2.358431,
"BYR": 21753.158037,
"BZD": 2.240616,
"CAD": 1.450148,
"CDF": 1870.1058,
"CHF": 1.074151,
"CLF": 0.03116,
"CLP": 859.807674,
"CNY": 7.60562,
"COP": 3698.602892,
"CRC": 626.092058,
"CUC": 1.109855,
"CUP": 29.411158,
"CVE": 110.289846,
"CZK": 25.153089,
"DJF": 197.243828,
"DKK": 7.47292,
"DOP": 59.102242,
"DZD": 132.756482,
"EGP": 17.553574,
"ERN": 16.648484,
"ETB": 35.580878,
"EUR": 1,
"FJD": 2.400845,
"FKP": 0.853386,
"GBP": 0.85344,
"GEL": 3.185507,
"GGP": 0.853386,
"GHS": 6.274513,
"GIP": 0.853386,
"GMD": 56.768832,
"GNF": 10596.012114,
"GTQ": 8.553126,
"GYD": 232.002258,
"HKD": 8.621204,
"HNL": 27.374523,
"HRK": 7.440676,
"HTG": 110.172276,
"HUF": 336.324934,
"IDR": 15156.512862,
"ILS": 3.83415,
"IMP": 0.853386,
"INR": 78.888694,
"IQD": 1326.938867,
"IRR": 46730.444914,
"ISK": 137.600239,
"JEP": 0.853386,
"JMD": 148.788893,
"JOD": 0.786908,
"JPY": 122.268839,
"KES": 111.928983,
"KGS": 77.501466,
"KHR": 4516.341065,
"KMF": 490.944654,
"KPW": 998.924351,
"KRW": 1285.001115,
"KWD": 0.336752,
"KYD": 0.926309,
"KZT": 418.614288,
"LAK": 9866.9219,
"LBP": 1680.878623,
"LKR": 201.462178,
"LRD": 212.54145,
"LSL": 15.97097,
"LTL": 3.277113,
"LVL": 0.67134,
"LYD": 1.554827,
"MAD": 10.670003,
"MDL": 19.504293,
"MGA": 4137.817131,
"MKD": 61.513856,
"MMK": 1635.120186,
"MNT": 3046.383998,
"MOP": 8.894003,
"MRO": 396.218091,
"MUR": 40.453985,
"MVR": 17.158186,
"MWK": 818.560908,
"MXN": 20.714833,
"MYR": 4.503235,
"MZN": 69.304855,
"NAD": 15.971063,
"NGN": 401.213027,
"NIO": 37.499305,
"NOK": 9.876378,
"NPR": 126.171668,
"NZD": 1.677113,
"OMR": 0.427107,
"PAB": 1.11155,
"PEN": 3.693532,
"PGK": 3.790442,
"PHP": 56.486625,
"PKR": 171.854321,
"PLN": 4.241811,
"PYG": 7245.891258,
"QAR": 4.041018,
"RON": 4.781705,
"RSD": 117.639084,
"RUB": 68.328666,
"RWF": 1054.94992,
"SAR": 4.164231,
"SBD": 9.212953,
"SCR": 15.197176,
"SDG": 50.109732,
"SEK": 10.554249,
"SGD": 1.495142,
"SHP": 0.853386,
"SLL": 10793.340217,
"SOS": 643.716193,
"SRD": 8.277332,
"STD": 23929.350626,
"SVC": 9.726191,
"SYP": 571.574016,
"SZL": 16.003797,
"THB": 33.726831,
"TJS": 10.776029,
"TMT": 3.884493,
"TND": 3.118141,
"TOP": 2.546506,
"TRY": 6.540514,
"TTD": 7.515693,
"TWD": 33.222957,
"TZS": 2562.435767,
"UAH": 27.00242,
"UGX": 4084.820116,
"USD": 1.109855,
"UYU": 41.508976,
"UZS": 10587.184569,
"VEF": 11.084676,
"VND": 25718.115031,
"VUV": 128.934974,
"WST": 2.923778,
"XAF": 656.137309,
"XAG": 0.061583,
"XAU": 0.000712,
"XCD": 2.999439,
"XDR": 0.804121,
"XOF": 656.137309,
"XPF": 119.286872,
"YER": 277.851936,
"ZAR": 16.027309,
"ZMK": 9990.030637,
"ZMW": 16.312283,
"ZWL": 357.373312
}
}
And this is you json that you have shown in the question.
Let me know if the Solution works for you.
Thanks
Related
Flutter: Group by Array List of Json String by Id
String jsonString = [{"color":"#000000","quantity":"100","price":"999","attribute":{"id":1,"name":"SIZE"}},{"color":"#cd7d96","quantity":"40","price":"555","attribute":{"id":2,"name":"FABRIC"}},{"color":"#66cccc","quantity":"500","price":"1000","attribute":{"id":1,"name":"SIZE"}}] How can I group by and archive results as below [{"attribute_id":1, "values":["#000000","#66cccc"]},{"attribute_id":2, "values":["#cd7d96"]}]
import 'dart:convert'; const raw = ''' [{"color":"#000000","quantity":"100","price":"999","attribute":{"id":1,"name":"Iphone 12"}},{"color":"#cd7d96","quantity":"40","price":"555","attribute":{"id":2,"name":"SAMSUNG"}},{"color":"#66cccc","quantity":"500","price":"1000","attribute":{"id":1,"name":"OPPO"}}] '''; typedef JMap = Map<String, dynamic>; typedef LJMap = List<JMap>; void groupById() { final data = (jsonDecode(raw) as List).cast<JMap>(); var result = <JMap>[]; data.map<int>((m) => m['attribute']['id']).toSet().forEach((e) { result.add({ 'attribute_id': e, 'values': data.where((m) => m['attribute']['id'] == e).map((m) => m['color']).toList(), }); }); print(result); } void main(List<String> args) { groupById(); } Output: [{attribute_id: 1, values: [#000000, #66cccc]}, {attribute_id: 2, values: [#cd7d96]}]
Flutter: ChangeNotifierProvider doesn't work with my MVVM architecture
I have a complex JSON object and I already converted it to dart code using JSON to Dart plugin. I have created a View Model to call my API and update the provider. However, the provider doesn't seem to work. The API response is successful but I get this error message -> The following NoSuchMethodError was thrown building Builder: The getter 'replyStatus' was called on null. Receiver: null Tried calling: replyStatus Can anyone help me to solve this issue? Below is the code I have. JSON to Dart Response class UserProfile { int replyStatus; String replyDesc; int debugStep; bool hasData; int actualDataSize; List<ResultObjectSet> resultObjectSet; dynamic token; UserProfile( {this.replyStatus, this.replyDesc, this.debugStep, this.hasData, this.actualDataSize, this.resultObjectSet, this.token}); UserProfile.fromJson(Map<String, dynamic> json) { replyStatus = json['ReplyStatus']; replyDesc = json['ReplyDesc']; debugStep = json['DebugStep']; hasData = json['HasData']; actualDataSize = json['ActualDataSize']; if (json['ResultObjectSet'] != null) { // ignore: deprecated_member_use resultObjectSet = new List<ResultObjectSet>(); json['ResultObjectSet'].forEach((v) { resultObjectSet.add(new ResultObjectSet.fromJson(v)); }); } token = json['Token']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['ReplyStatus'] = this.replyStatus; data['ReplyDesc'] = this.replyDesc; data['DebugStep'] = this.debugStep; data['HasData'] = this.hasData; data['ActualDataSize'] = this.actualDataSize; if (this.resultObjectSet != null) { data['ResultObjectSet'] = this.resultObjectSet.map((v) => v.toJson()).toList(); } data['Token'] = this.token; return data; } } class ResultObjectSet { String objectName; ObjectSet objectSet; ResultObjectSet({this.objectName, this.objectSet}); ResultObjectSet.fromJson(Map<String, dynamic> json) { objectName = json['ObjectName']; objectSet = json['ObjectSet'] != null ? new ObjectSet.fromJson(json['ObjectSet']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['ObjectName'] = this.objectName; if (this.objectSet != null) { data['ObjectSet'] = this.objectSet.toJson(); } return data; } } class ObjectSet { int userId; String userName; String regsterEmail; String lastLogin; double displayTimeZone; int accountStatus; int language; List<UserCompany> userCompany; MenuOption menuOption; bool pnmDisableFlag; ObjectSet( {this.userId, this.userName, this.regsterEmail, this.lastLogin, this.displayTimeZone, this.accountStatus, this.language, this.userCompany, this.menuOption, this.pnmDisableFlag}); ObjectSet.fromJson(Map<String, dynamic> json) { userId = json['UserId']; userName = json['UserName']; regsterEmail = json['RegsterEmail']; lastLogin = json['LastLogin']; displayTimeZone = json['DisplayTimeZone']; accountStatus = json['AccountStatus']; language = json['Language']; if (json['UserCompany'] != null) { // ignore: deprecated_member_use userCompany = new List<UserCompany>(); json['UserCompany'].forEach((v) { userCompany.add(new UserCompany.fromJson(v)); }); } menuOption = json['MenuOption'] != null ? new MenuOption.fromJson(json['MenuOption']) : null; pnmDisableFlag = json['PnmDisableFlag']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['UserId'] = this.userId; data['UserName'] = this.userName; data['RegsterEmail'] = this.regsterEmail; data['LastLogin'] = this.lastLogin; data['DisplayTimeZone'] = this.displayTimeZone; data['AccountStatus'] = this.accountStatus; data['Language'] = this.language; if (this.userCompany != null) { data['UserCompany'] = this.userCompany.map((v) => v.toJson()).toList(); } if (this.menuOption != null) { data['MenuOption'] = this.menuOption.toJson(); } data['PnmDisableFlag'] = this.pnmDisableFlag; return data; } } class UserCompany { int companyId; String companyName; int typeUserRoleId; String typeUserRoleDesc; int menuRights; int reportRights; ManagementCompanyRights managementCompanyRights; ManagementCompanyRights managementUserRights; ManagementCompanyRights managementUserRole; ManagementCompanyRights managementFleetRights; ManagementCompanyRights managementShipRights; UserCompany( {this.companyId, this.companyName, this.typeUserRoleId, this.typeUserRoleDesc, this.menuRights, this.reportRights, this.managementCompanyRights, this.managementUserRights, this.managementUserRole, this.managementFleetRights, this.managementShipRights}); UserCompany.fromJson(Map<String, dynamic> json) { companyId = json['CompanyId']; companyName = json['CompanyName']; typeUserRoleId = json['TypeUserRoleId']; typeUserRoleDesc = json['TypeUserRoleDesc']; menuRights = json['MenuRights']; reportRights = json['ReportRights']; managementCompanyRights = json['ManagementCompanyRights'] != null ? new ManagementCompanyRights.fromJson(json['ManagementCompanyRights']) : null; managementUserRights = json['ManagementUserRights'] != null ? new ManagementCompanyRights.fromJson(json['ManagementUserRights']) : null; managementUserRole = json['ManagementUserRole'] != null ? new ManagementCompanyRights.fromJson(json['ManagementUserRole']) : null; managementFleetRights = json['ManagementFleetRights'] != null ? new ManagementCompanyRights.fromJson(json['ManagementFleetRights']) : null; managementShipRights = json['ManagementShipRights'] != null ? new ManagementCompanyRights.fromJson(json['ManagementShipRights']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['CompanyId'] = this.companyId; data['CompanyName'] = this.companyName; data['TypeUserRoleId'] = this.typeUserRoleId; data['TypeUserRoleDesc'] = this.typeUserRoleDesc; data['MenuRights'] = this.menuRights; data['ReportRights'] = this.reportRights; if (this.managementCompanyRights != null) { data['ManagementCompanyRights'] = this.managementCompanyRights.toJson(); } if (this.managementUserRights != null) { data['ManagementUserRights'] = this.managementUserRights.toJson(); } if (this.managementUserRole != null) { data['ManagementUserRole'] = this.managementUserRole.toJson(); } if (this.managementFleetRights != null) { data['ManagementFleetRights'] = this.managementFleetRights.toJson(); } if (this.managementShipRights != null) { data['ManagementShipRights'] = this.managementShipRights.toJson(); } return data; } } class ManagementCompanyRights { bool add; bool edit; bool delete; bool fleetAssignment; ManagementCompanyRights( {this.add, this.edit, this.delete, this.fleetAssignment}); ManagementCompanyRights.fromJson(Map<String, dynamic> json) { add = json['Add']; edit = json['Edit']; delete = json['Delete']; fleetAssignment = json['FleetAssignment']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['Add'] = this.add; data['Edit'] = this.edit; data['Delete'] = this.delete; data['FleetAssignment'] = this.fleetAssignment; return data; } } class MenuOption { bool dashBoard; bool fuelCons; bool bunkering; bool aMS; bool shaftPower; bool kpiPerformance; bool eOM; bool route; bool report; bool management; MenuOption( {this.dashBoard, this.fuelCons, this.bunkering, this.aMS, this.shaftPower, this.kpiPerformance, this.eOM, this.route, this.report, this.management}); MenuOption.fromJson(Map<String, dynamic> json) { dashBoard = json['DashBoard']; fuelCons = json['FuelCons']; bunkering = json['Bunkering']; aMS = json['AMS']; shaftPower = json['ShaftPower']; kpiPerformance = json['KpiPerformance']; eOM = json['EOM']; route = json['Route']; report = json['Report']; management = json['Management']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['DashBoard'] = this.dashBoard; data['FuelCons'] = this.fuelCons; data['Bunkering'] = this.bunkering; data['AMS'] = this.aMS; data['ShaftPower'] = this.shaftPower; data['KpiPerformance'] = this.kpiPerformance; data['EOM'] = this.eOM; data['Route'] = this.route; data['Report'] = this.report; data['Management'] = this.management; return data; } } Main.Dart class MyApp extends StatelessWidget { // This widget is the root of your application. #override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider( create: (context) => UserVM(), ), ], child: MaterialApp( initialRoute: LoginScreen.id, routes: { LoginScreen.id: (context) => LoginScreen(), SelectCompany.id: (context) => SelectCompany(), }, ), ); } } My API class class LoginScreenApi { var dio = Dio(); Future<UserProfile> authenticateUser( String email, String password, String token) async { try { String queryURL = '$domainURL/User/LoginMobile?Email=$email&UserPassword=$password&MobileDeviceTokenId=$token'; Response response = await dio.get(queryURL); print('login status: ${response.statusCode}'); if (response.statusCode == 200) { UserProfile user = UserProfile.fromJson(response.data); return user; } return null; } catch (e) { print(e); return null; } } } My VM class class UserVM extends ChangeNotifier { UserProfile user; UserVM({this.user}); /// Call Login API Future<void> authenticateUser( String email, String password, String token) async { final results = await LoginScreenApi().authenticateUser(email, password, token); /// if login successfully, save the USER result and route to select company page if (results != null) { this.user = results; notifyListeners(); Navigator.pushNamed(navigatorKey.currentContext, SelectCompany.id); } else { showDialog( context: navigatorKey.currentContext, builder: (BuildContext context) { return PopUpDialog( text: 'Wrong User ID or Password!', ); }); } } } The screen that I display the data from my provider class _SelectCompanyState extends State<SelectCompany> { #override #override Widget build(BuildContext context) { return Scaffold( body: Container( child: Text( '${Provider.of<UserVM>(context, listen: false).replyStatus}', style: TextStyle(color: Colors.black), ), ), ); } } The Widget that call the Authenticate method at my login screen Widget _loginButton() { // ignore: deprecated_member_use return RaisedButton( onPressed: () async { await user.authenticateUser(email, password, deviceToken); setState(() { showSpinner = true; }); }, color: Colors.black, child: Text( '${userLanguage == 'chinese' ? '登入' : 'Login'}', style: TextStyle(fontSize: 15, color: Colors.yellow, fontFamily: 'Roboto'), ), shape: RoundedRectangleBorder( side: BorderSide(color: Colors.lightBlueAccent)), ); }
The following line loads an instance of your UserVM. final userVM = Provider<UserVM>.of(context,listen:false); Your UserVM class doesn't have a property called replyStatus, it's your UserProfile class that does. So call it like this: final replyStatus = userVM.user.replyStatus; Note: Your user can also be null since you're not passing it while creating the UserVM(). Neither are you calling the authenticate method for user to be updated with results. If you're handling that somewhere else in your code that's fine else you need to check user for null as well before calling: final replyStatus; If(userVM.user! = null) replyStatus = userVM.user.replyStatus; else //<-- some alternative here
How to get data this nested list json with volley?
URL: https://api.alquran.cloud/v1/quran/quran-uthmani I want to receive the data at this address, but I cannot get data from the list named "surah" in the data. Can you help me? How to solve this problem? I can show the "data" list but I don't know how to get the "surah" arry in it. My java code: String url = "https://api.alquran.cloud/v1/quran/quran-uthmani"; StringRequest istek = new StringRequest( Request.Method.GET, url, new Response.Listener<String>() { #Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject( response ); Log.e( "ilkData", "test" ); JSONArray kuranMainListe = jsonObject.getJSONArray( "data" ); JSONArray surahMainListe = kuranMainListe.getJSONArray( 0 ); for (int i = 0; i < surahMainListe.length(); i++) { JSONObject sureler = surahMainListe.getJSONObject( i ); JSONObject sure = sureler.getJSONObject( "Surahs" ); int sureNumber = sureler.getInt( "number" ); String sureName = sureler.getString( "name" ); String sureEnName = sureler.getString( "englishName" ); String sureEnCeviri = sureler.getString( "englishNameTranslation" ); String sureVahiyTuru = sureler.getString( "revelationType" ); Log.e( "sureAdi", sureName ); JSONArray ayetlerListe = jsonObject.getJSONArray( "ayahs" ); for (int a = 0; a < ayetlerListe.length(); a++) { JSONObject ayetler = ayetlerListe.getJSONObject( a ); int ayetNumber = ayetler.getInt( "number" ); String ayettext = ayetler.getString( "text" ); int ayetnumberInSurah = ayetler.getInt( "numberInSurah" ); int ayetjuz = ayetler.getInt( "juz" ); int ayetmanzil = ayetler.getInt( "manzil" ); int ayetpage = ayetler.getInt( "page" ); int ayetruku = ayetler.getInt( "ruku" ); int ayethizbQuarter = ayetler.getInt( "hizbQuarter" ); String ayetSajda = ayetler.getString( "sajda" ); Log.e( "ayetNumarasi", String.valueOf( ayetNumber ) ); } } } catch (JSONException e) { e.printStackTrace(); Log.e( "hataCatch", String.valueOf( e ) ); } } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { Log.e( "volleyHata", String.valueOf( error ) ); } } ); istek.setRetryPolicy( new DefaultRetryPolicy( 10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT ) ); Volley.newRequestQueue( KuranOkuBendenAyarlar.this ).add( istek );
I fixed this problem. I have overlooked that the curly brackets are "{" object, the square bracket is "[" array.
Error: type 'String' is not a subtype of type 'List<dynamic>'
I want to fetch dat form some API and parse its data to model. MyModel: class SetupIdeaModel { String id; String userId; String typeIdea = "Implemented Idea"; String category; //Or Industry String experienceYear; String experienceMonth; String ideaHeadline; String ideaText; Map timeline = { "timelineType": "date", "details": null, }; List documents = []; Map uploadVideo; String location; String estimatedPeople; Map whitePaper; bool needServiceProvider = false; bool needInvestor = true; } } and I fetch data from the API with the getIdeaList method: getIdeaList method Future getIdeaList(String token) async { Response response = await APIRequest().get( myUrl: "$baseUrl/innovator/idea/list", token: token, ); //Parsing ideaList to SetupIdeaModel ideas = List(); try { (response.data as List).forEach((element) { SetupIdeaModel idea = new SetupIdeaModel(); var months = int.parse(element["industryExperienceInMonth"]); var year = (months / 12).floor(); var remainderMonths = months % 12; print("$year year and $remainderMonths months"); idea.id = element["_id"]; idea.userId = element["userId"]; idea.typeIdea = element["ideaType"]; idea.category = element["industry"]; idea.experienceYear = year.toString(); idea.experienceMonth = remainderMonths.toString(); idea.ideaHeadline = element["headline"]; idea.ideaText = element["idea"]; idea.estimatedPeople = element["estimatedPeople"].toString(); print("Documents ${element["uploadDocuments"]}"); idea.location = element["targetAudience"]; idea.documents = element["uploadDocuments"]; // idea.timeline = element["timeline"]; // idea.uploadVideo = element["uploadVideo"]; ideas.add(idea); }); } catch (e) { print("Error: $e"); } print("ideas $ideas"); notifyListeners(); } Everything is OK but When I add one of these line: idea.documents = element["uploadDocuments"]; idea.timeline = element["timeline"]; idea.uploadVideo = element["uploadVideo"]; I have got the error. The data comes for the API is like this: [ { "industryExperienceInMonth":30, "estimatedPeople":200, "needServiceProvider":true, "needInvestor":true, "_id":5fcc681fc5b4260011810112, "userId":5fb6650eacc60d0011910a9b, "ideaType":"Implemented Idea", "industry":"Technalogy", "headline":"IDea headline", "idea":"This is aobut your idea", "timeline":{ "timelineType":"date", "details":{ "date":Dec 6, 2020 } }, "uploadDocuments":[ { "_id":5fcc6804c5b4260011810110, "uriPath":"https"://webfume-onionai.s3.amazonaws.com/guest/public/document/741333-beats_by_dre-wallpaper-1366x768.jpg } ], "uploadVideo":{ "_id":5fcc681ac5b4260011810111, "uriPath":"https"://webfume-onionai.s3.amazonaws.com/guest/public/video/588700-beats_by_dre-wallpaper-1366x768.jpg }, "targetAudience":"heart", "__v":0 } ] I'm using Dio package. The documents in the model is a list and the uploadDocuments the come form API is a list too. But Why I got this error.
Your JSON data has some syntax errors that's why it's not working. All the UIDs and URLs should be in string format and you should Serializing JSON inside model classes. see also I have fix some error in your code and did some improvement : Future getIdeaList(String token) async { List<SetupIdeaModel> setupIdeaModel = List(); try { Response response = await APIRequest().get( myUrl: "$baseUrl/innovator/idea/list", token: token, ); if (response.statusCode == 200) { List<SetupIdeaModel> apiData = (json.decode(utf8.decode(response.data)) as List) .map((data) => new SetupIdeaModel.fromJson(data)) .toList(); setupIdeaModel.addAll(apiData); } } catch (e) { print("Error: $e"); } } This is the model class : class SetupIdeaModel { int industryExperienceInMonth; int estimatedPeople; bool needServiceProvider; bool needInvestor; String sId; String userId; String ideaType; String industry; String headline; String idea; Timeline timeline; List<UploadDocuments> uploadDocuments; UploadDocuments uploadVideo; String targetAudience; int iV; SetupIdeaModel( {this.industryExperienceInMonth, this.estimatedPeople, this.needServiceProvider, this.needInvestor, this.sId, this.userId, this.ideaType, this.industry, this.headline, this.idea, this.timeline, this.uploadDocuments, this.uploadVideo, this.targetAudience, this.iV}); SetupIdeaModel.fromJson(Map<String, dynamic> json) { industryExperienceInMonth = json['industryExperienceInMonth']; estimatedPeople = json['estimatedPeople']; needServiceProvider = json['needServiceProvider']; needInvestor = json['needInvestor']; sId = json['_id']; userId = json['userId']; ideaType = json['ideaType']; industry = json['industry']; headline = json['headline']; idea = json['idea']; timeline = json['timeline'] != null ? new Timeline.fromJson(json['timeline']) : null; if (json['uploadDocuments'] != null) { uploadDocuments = new List<UploadDocuments>(); json['uploadDocuments'].forEach((v) { uploadDocuments.add(new UploadDocuments.fromJson(v)); }); } uploadVideo = json['uploadVideo'] != null ? new UploadDocuments.fromJson(json['uploadVideo']) : null; targetAudience = json['targetAudience']; iV = json['__v']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['industryExperienceInMonth'] = this.industryExperienceInMonth; data['estimatedPeople'] = this.estimatedPeople; data['needServiceProvider'] = this.needServiceProvider; data['needInvestor'] = this.needInvestor; data['_id'] = this.sId; data['userId'] = this.userId; data['ideaType'] = this.ideaType; data['industry'] = this.industry; data['headline'] = this.headline; data['idea'] = this.idea; if (this.timeline != null) { data['timeline'] = this.timeline.toJson(); } if (this.uploadDocuments != null) { data['uploadDocuments'] = this.uploadDocuments.map((v) => v.toJson()).toList(); } if (this.uploadVideo != null) { data['uploadVideo'] = this.uploadVideo.toJson(); } data['targetAudience'] = this.targetAudience; data['__v'] = this.iV; return data; } } class Timeline { String timelineType; Details details; Timeline({this.timelineType, this.details}); Timeline.fromJson(Map<String, dynamic> json) { timelineType = json['timelineType']; details = json['details'] != null ? new Details.fromJson(json['details']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['timelineType'] = this.timelineType; if (this.details != null) { data['details'] = this.details.toJson(); } return data; } } class Details { String date; Details({this.date}); Details.fromJson(Map<String, dynamic> json) { date = json['date']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['date'] = this.date; return data; } } class UploadDocuments { String sId; String uriPath; UploadDocuments({this.sId, this.uriPath}); UploadDocuments.fromJson(Map<String, dynamic> json) { sId = json['_id']; uriPath = json['uriPath']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['_id'] = this.sId; data['uriPath'] = this.uriPath; return data; } }
how to filx Unexpected character (at char 1) in flutter
hy we have a radio server with the followoing json file { "icestats":{ "admin":"icemaster#localhost", "host":"online.localhost.be", "location":"Earth", "server_id":"Icecast 2.4.4", "server_start":"Sun, 30 Aug 2020 10:50:52 +0200", "server_start_iso8601":"2020-08-30T10:50:52+0200", "source":[ { "audio_info":"ice-samplerate=44100;ice-bitrate=320;ice-channels=2", "bitrate":320, "genre":"oldies", "ice-bitrate":320, "ice-channels":2, "ice-samplerate":44100, "listener_peak":0, "listeners":0, "listenurl":"http://127.0.0.1:8000/mp3_320", "server_description":"Very Oldies!", "server_name":"loclahost", "server_type":"audio/mpeg", "server_url":"https://127.0.0.1:8000", "stream_start":"Sun, 30 Aug 2020 13:45:16 +0200", "stream_start_iso8601":"2020-08-30T13:45:16+0200", "title":"1951: Four Knights - I Love The Sunshine Of Your Smile", "dummy":null }, { "audio_bitrate":320000, "audio_channels":2, "audio_info":"ice-samplerate=44100;ice-bitrate=320;ice-channels=2", "audio_samplerate":44100, "bitrate":320, "genre":"oldies", "ice-bitrate":320, "ice-channels":2, "ice-samplerate":44100, "listener_peak":0, "listeners":0, "listenurl":"http://127.0.0.1:8000/ogg_320", "server_description":"Very Oldies!", "server_name":"localhost", "server_type":"application/ogg", "server_url":"https://127.0.0.1:8000", "stream_start":"Sun, 30 Aug 2020 13:45:16 +0200", "stream_start_iso8601":"2020-08-30T13:45:16+0200", "subtype":"Vorbis", "dummy":null } ] } } if io parse this with this model i get the error 'unexpected charcater at 1' class Autogenerated { Icestats icestats; Autogenerated({this.icestats}); Autogenerated.fromJson(Map<String, dynamic> json) { icestats = json['icestats'] != null ? new Icestats.fromJson(json['icestats']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); if (this.icestats != null) { data['icestats'] = this.icestats.toJson(); } return data; } } class Icestats { String admin; String host; String location; String serverId; String serverStart; String serverStartIso8601; List<Source> source; Icestats( {this.admin, this.host, this.location, this.serverId, this.serverStart, this.serverStartIso8601, this.source}); Icestats.fromJson(Map<String, dynamic> json) { admin = json['admin']; host = json['host']; location = json['location']; serverId = json['server_id']; serverStart = json['server_start']; serverStartIso8601 = json['server_start_iso8601']; if (json['source'] != null) { source = new List<Source>(); json['source'].forEach((v) { source.add(new Source.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['admin'] = this.admin; data['host'] = this.host; data['location'] = this.location; data['server_id'] = this.serverId; data['server_start'] = this.serverStart; data['server_start_iso8601'] = this.serverStartIso8601; if (this.source != null) { data['source'] = this.source.map((v) => v.toJson()).toList(); } return data; } } class Source { String audioInfo; int bitrate; String genre; int iceBitrate; int iceChannels; int iceSamplerate; int listenerPeak; int listeners; String listenurl; String serverDescription; String serverName; String serverType; String serverUrl; String streamStart; String streamStartIso8601; String title; Null dummy; int audioBitrate; int audioChannels; int audioSamplerate; String subtype; Source( {this.audioInfo, this.bitrate, this.genre, this.iceBitrate, this.iceChannels, this.iceSamplerate, this.listenerPeak, this.listeners, this.listenurl, this.serverDescription, this.serverName, this.serverType, this.serverUrl, this.streamStart, this.streamStartIso8601, this.title, this.dummy, this.audioBitrate, this.audioChannels, this.audioSamplerate, this.subtype}); Source.fromJson(Map<String, dynamic> json) { audioInfo = json['audio_info']; bitrate = json['bitrate']; genre = json['genre']; iceBitrate = json['ice-bitrate']; iceChannels = json['ice-channels']; iceSamplerate = json['ice-samplerate']; listenerPeak = json['listener_peak']; listeners = json['listeners']; listenurl = json['listenurl']; serverDescription = json['server_description']; serverName = json['server_name']; serverType = json['server_type']; serverUrl = json['server_url']; streamStart = json['stream_start']; streamStartIso8601 = json['stream_start_iso8601']; title = json['title']; dummy = json['dummy']; audioBitrate = json['audio_bitrate']; audioChannels = json['audio_channels']; audioSamplerate = json['audio_samplerate']; subtype = json['subtype']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['audio_info'] = this.audioInfo; data['bitrate'] = this.bitrate; data['genre'] = this.genre; data['ice-bitrate'] = this.iceBitrate; data['ice-channels'] = this.iceChannels; data['ice-samplerate'] = this.iceSamplerate; data['listener_peak'] = this.listenerPeak; data['listeners'] = this.listeners; data['listenurl'] = this.listenurl; data['server_description'] = this.serverDescription; data['server_name'] = this.serverName; data['server_type'] = this.serverType; data['server_url'] = this.serverUrl; data['stream_start'] = this.streamStart; data['stream_start_iso8601'] = this.streamStartIso8601; data['title'] = this.title; data['dummy'] = this.dummy; data['audio_bitrate'] = this.audioBitrate; data['audio_channels'] = this.audioChannels; data['audio_samplerate'] = this.audioSamplerate; data['subtype'] = this.subtype; return data; } } the code i have used i pretty simple this is the code i have used. if i parse the same code with a simple xml structure this works but with the icecast parsing this does not succeed. please advice me var JsonData = 'http://127.0.0.1:8000/status-json.xsl'; var parsedJson = json.decode(JsonData); var title = Source.fromJson(parsedJson); is the json formatting of the icecast server incorrect ? it starts with a { update 1 class User { String title; User(Map<String, dynamic> data){ title = data['title']; } } Future<Source> fetchData() async{ var jsonData = 'http://online.doobeedoo.be:8000/status-json.xsl'; final response = await http.get(jsonData); //wacht to de data is ontvangen (200) if(response.statusCode == 200) { var parsedJson = json.decode(response.body); //parsen van response var user = User(parsedJson); return('${user.title}'); //error here (A value of type 'String' can't be returned from function 'fetchData' because it has a return type of 'Future<Source>'.) } else { throw Exception('Failed to load status.json response file'); } }
Use the http package to make a request to your server and retrieve a response. Then parse the JSON the way your currently have it. You're currently parsing a String URL. Not a JSON. import 'package:http/http.dart' as http; var url = 'http://127.0.0.1:8000/status-json.xsl'; var response = await http.get(url);//Actually get the data at the URL var parsedJson = json.decode(response.body);//Parse the response var title = Source.fromJson(parsedJson);