I am learning flutter and trying to parse a JSON just like in this article, but getting this error.
lib/service/apiservice.dart:11:33: Error: A value of type 'Data' can't be assigned to a variable of type 'List'. - 'Data' is from 'package:gocorona/models/totals.dart' ('lib/models/totals.dart'). - 'List' is from 'dart:core'. final List data = dataFromJson(response.body);
lib/service/apiservice.dart
import 'package:http/http.dart' as http;
import 'package:gocorona/models/totals.dart';
class ApiServices {
static const String url = 'https://api.rootnet.in/covid19-in/stats/latest';
static Future<List<Data>> getDataFromAPI() async {
try {
final response = await http.get(url);
if (200 == response.statusCode) {
final List<Data> data = dataFromJson(response.body);
return data;
} else {
return List<Data>();
}
} catch (e) {
return List<Data>();
}
}
}
lib/models/totals.dart
import 'dart:convert';
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
bool success;
DataClass data;
DateTime lastRefreshed;
DateTime lastOriginUpdate;
Data({
this.success,
this.data,
this.lastRefreshed,
this.lastOriginUpdate,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
success: json["success"],
data: DataClass.fromJson(json["data"]),
lastRefreshed: DateTime.parse(json["lastRefreshed"]),
lastOriginUpdate: DateTime.parse(json["lastOriginUpdate"]),
);
Map<String, dynamic> toJson() => {
"success": success,
"data": data.toJson(),
"lastRefreshed": lastRefreshed.toIso8601String(),
"lastOriginUpdate": lastOriginUpdate.toIso8601String(),
};
}
class DataClass {
Summary summary;
List<UnofficialSummary> unofficialSummary;
List<Regional> regional;
DataClass({
this.summary,
this.unofficialSummary,
this.regional,
});
factory DataClass.fromJson(Map<String, dynamic> json) => DataClass(
summary: Summary.fromJson(json["summary"]),
unofficialSummary: List<UnofficialSummary>.from(json["unofficial-summary"].map((x) => UnofficialSummary.fromJson(x))),
regional: List<Regional>.from(json["regional"].map((x) => Regional.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"summary": summary.toJson(),
"unofficial-summary": List<dynamic>.from(unofficialSummary.map((x) => x.toJson())),
"regional": List<dynamic>.from(regional.map((x) => x.toJson())),
};
}
class Regional {
String loc;
int confirmedCasesIndian;
int discharged;
int deaths;
int confirmedCasesForeign;
int totalConfirmed;
Regional({
this.loc,
this.confirmedCasesIndian,
this.discharged,
this.deaths,
this.confirmedCasesForeign,
this.totalConfirmed,
});
factory Regional.fromJson(Map<String, dynamic> json) => Regional(
loc: json["loc"],
confirmedCasesIndian: json["confirmedCasesIndian"],
discharged: json["discharged"],
deaths: json["deaths"],
confirmedCasesForeign: json["confirmedCasesForeign"],
totalConfirmed: json["totalConfirmed"],
);
Map<String, dynamic> toJson() => {
"loc": loc,
"confirmedCasesIndian": confirmedCasesIndian,
"discharged": discharged,
"deaths": deaths,
"confirmedCasesForeign": confirmedCasesForeign,
"totalConfirmed": totalConfirmed,
};
}
class Summary {
int total;
int confirmedCasesIndian;
int confirmedCasesForeign;
int discharged;
int deaths;
int confirmedButLocationUnidentified;
Summary({
this.total,
this.confirmedCasesIndian,
this.confirmedCasesForeign,
this.discharged,
this.deaths,
this.confirmedButLocationUnidentified,
});
factory Summary.fromJson(Map<String, dynamic> json) => Summary(
total: json["total"],
confirmedCasesIndian: json["confirmedCasesIndian"],
confirmedCasesForeign: json["confirmedCasesForeign"],
discharged: json["discharged"],
deaths: json["deaths"],
confirmedButLocationUnidentified: json["confirmedButLocationUnidentified"],
);
Map<String, dynamic> toJson() => {
"total": total,
"confirmedCasesIndian": confirmedCasesIndian,
"confirmedCasesForeign": confirmedCasesForeign,
"discharged": discharged,
"deaths": deaths,
"confirmedButLocationUnidentified": confirmedButLocationUnidentified,
};
}
class UnofficialSummary {
String source;
int total;
int recovered;
int deaths;
int active;
UnofficialSummary({
this.source,
this.total,
this.recovered,
this.deaths,
this.active,
});
factory UnofficialSummary.fromJson(Map<String, dynamic> json) => UnofficialSummary(
source: json["source"],
total: json["total"],
recovered: json["recovered"],
deaths: json["deaths"],
active: json["active"],
);
Map<String, dynamic> toJson() => {
"source": source,
"total": total,
"recovered": recovered,
"deaths": deaths,
"active": active,
};
}
lib/screens/states.dart
import 'package:flutter/material.dart';
import 'package:gocorona/models/totals.dart';
import 'package:gocorona/service/apiservice.dart';
class Statewise extends StatefulWidget {
@override
_StatewiseState createState() => _StatewiseState();
}
class _StatewiseState extends State<Statewise> {
List<Data> _datafromApi;
bool _isloading;
@override
void initState() {
super.initState();
_isloading = true;
ApiServices.getDataFromAPI().then((data) {
setState(() {
_datafromApi = data;
_isloading = false;
});
});
}
@override
Widget build(BuildContext context) {
if (_isloading) {
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
} else {
return Scaffold(
body: ListView.builder(
itemCount: _datafromApi == null ? 0 : _datafromApi.length,
itemBuilder: (context, index) {
Data datas = _datafromApi[index];
print(datas?.toString() ?? "Empty");
return ListTile(
title: Text(
datas.data.regional[0].loc.toString(),
style: TextStyle(color: Colors.black),
));
}),
);
}
}
}
Compiler message:
lib/service/apiservice.dart:11:33: Error: A value of type 'Data' can't be assigned to a variable of type 'List<Data>'.
- 'Data' is from 'package:gocorona/models/totals.dart' ('lib/models/totals.dart').
- 'List' is from 'dart:core'.
final List<Data> data = dataFromJson(response.body);
^
flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.17.0, on Microsoft Windows [Version 10.0.18362.778], locale en-IN)
[√] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[√] Android Studio (version 3.6)
[√] VS Code (version 1.45.0)
[√] Connected device (1 available)
• No issues found!
This was happening because you was returning only data from constructor and you was trying to accept it as a List.
I made a few changes i hope it will help you.
class ApiServices {
static const String url = 'https://api.rootnet.in/covid19-in/stats/latest';
static Future<Data> getDataFromAPI() async {
try {
final response = await http.get(url);
if (200 == response.statusCode) {
print(response.toString());
final data = dataFromJson(response.body);
// print(data);
return data;
} else {
return Data();
}
} catch (e) {
return Data();
}
}
}
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
bool success;
DataClass data;
DateTime lastRefreshed;
DateTime lastOriginUpdate;
Data({
this.success,
this.data,
this.lastRefreshed,
this.lastOriginUpdate,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
success: json["success"],
data: DataClass.fromJson(json["data"]),
lastRefreshed: DateTime.parse(json["lastRefreshed"]),
lastOriginUpdate: DateTime.parse(json["lastOriginUpdate"]),
);
Map<String, dynamic> toJson() => {
"success": success,
"data": data.toJson(),
"lastRefreshed": lastRefreshed.toIso8601String(),
"lastOriginUpdate": lastOriginUpdate.toIso8601String(),
};
}
class DataClass {
Summary summary;
List<UnofficialSummary> unofficialSummary;
List<Regional> regional;
DataClass({
this.summary,
this.unofficialSummary,
this.regional,
});
factory DataClass.fromJson(Map<String, dynamic> json) => DataClass(
summary: Summary.fromJson(json["summary"]),
unofficialSummary: List<UnofficialSummary>.from(
json["unofficial-summary"]
.map((x) => UnofficialSummary.fromJson(x))),
regional: List<Regional>.from(
json["regional"].map((x) => Regional.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"summary": summary.toJson(),
"unofficial-summary":
List<dynamic>.from(unofficialSummary.map((x) => x.toJson())),
"regional": List<dynamic>.from(regional.map((x) => x.toJson())),
};
}
class Regional {
String loc;
int confirmedCasesIndian;
int discharged;
int deaths;
int confirmedCasesForeign;
int totalConfirmed;
Regional({
this.loc,
this.confirmedCasesIndian,
this.discharged,
this.deaths,
this.confirmedCasesForeign,
this.totalConfirmed,
});
factory Regional.fromJson(Map<String, dynamic> json) => Regional(
loc: json["loc"],
confirmedCasesIndian: json["confirmedCasesIndian"],
discharged: json["discharged"],
deaths: json["deaths"],
confirmedCasesForeign: json["confirmedCasesForeign"],
totalConfirmed: json["totalConfirmed"],
);
Map<String, dynamic> toJson() => {
"loc": loc,
"confirmedCasesIndian": confirmedCasesIndian,
"discharged": discharged,
"deaths": deaths,
"confirmedCasesForeign": confirmedCasesForeign,
"totalConfirmed": totalConfirmed,
};
}
class Summary {
int total;
int confirmedCasesIndian;
int confirmedCasesForeign;
int discharged;
int deaths;
int confirmedButLocationUnidentified;
Summary({
this.total,
this.confirmedCasesIndian,
this.confirmedCasesForeign,
this.discharged,
this.deaths,
this.confirmedButLocationUnidentified,
});
factory Summary.fromJson(Map<String, dynamic> json) => Summary(
total: json["total"],
confirmedCasesIndian: json["confirmedCasesIndian"],
confirmedCasesForeign: json["confirmedCasesForeign"],
discharged: json["discharged"],
deaths: json["deaths"],
confirmedButLocationUnidentified:
json["confirmedButLocationUnidentified"],
);
Map<String, dynamic> toJson() => {
"total": total,
"confirmedCasesIndian": confirmedCasesIndian,
"confirmedCasesForeign": confirmedCasesForeign,
"discharged": discharged,
"deaths": deaths,
"confirmedButLocationUnidentified": confirmedButLocationUnidentified,
};
}
class UnofficialSummary {
String source;
int total;
int recovered;
int deaths;
int active;
UnofficialSummary({
this.source,
this.total,
this.recovered,
this.deaths,
this.active,
});
factory UnofficialSummary.fromJson(Map<String, dynamic> json) =>
UnofficialSummary(
source: json["source"],
total: json["total"],
recovered: json["recovered"],
deaths: json["deaths"],
active: json["active"],
);
Map<String, dynamic> toJson() => {
"source": source,
"total": total,
"recovered": recovered,
"deaths": deaths,
"active": active,
};
}
class Statewise extends StatefulWidget {
@override
_StatewiseState createState() => _StatewiseState();
}
class _StatewiseState extends State<Statewise> {
Data _datafromApi;
bool _isloading;
@override
void initState() {
super.initState();
_isloading = true;
ApiServices.getDataFromAPI().then((data) {
setState(() {
_datafromApi = data;
_isloading = false;
});
});
}
@override
Widget build(BuildContext context) {
if (_isloading) {
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
} else {
return Scaffold(
body: ListView.builder(
itemCount:
_datafromApi == null ? 0 : _datafromApi.data.regional.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
_datafromApi.data.regional[index].loc.toString(),
style: TextStyle(color: Colors.black),
));
}),
);
}
}
}