I'm new to Flutter and I'm trying to create an application with a ListView using this API: https://metmuseum.github.io/#search. Here is my code:
main.dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'user.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MET',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<List<User>> usersFuture = getUsers();
static Future<List<User>> getUsers() async {
var body;
for (int i = 0; i < 5; i++) {
String url =
'https://collectionapi.metmuseum.org/public/collection/v1/objects/$i';
var response = await http.get(Uri.parse(url));
body = json.decode(response.body);
}
return body.map<User>(User.fromJson).toList();
}
#override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text("Metropolitan Museum of Art"),
centerTitle: true,
),
body: Center(
child: FutureBuilder<List<User>>(
future: usersFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
} /*else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
final users = snapshot.data!;
return buildUsers(users);
}*/
final users = snapshot.data!;
return buildUsers(users);
},
),
),
);
Widget buildUsers(List<User> users) => ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
final user = users[index];
return Card(
child: ListTile(
leading: CircleAvatar(
radius: 28,
backgroundImage: NetworkImage(user.primaryImageSmall),
),
title: Text(user.title),
subtitle: Text(user.artistDisplayName),
),
);
},
);
}
user.dart
import 'package:flutter/material.dart';
class User {
final int objectID;
final bool isHighlight;
final String accessionYear;
final String primaryImage;
final String primaryImageSmall;
final String department;
final String objectName;
final String title;
final String culture;
final String period;
final String artistPrefix; //da usare prima dell'artista
final String artistDisplayName;
final String artistDisplayBio;
final String medium; //Refers to the materials that were used to create the artwork
final String dimensions;
final String geographyType; //da usare prima della città in cui è stata fatta l'opera
final String city;
final String state;
final String classification;
final String linkResource;
final String GalleryNumber;
const User(
{required this.objectID,
required this.isHighlight,
required this.accessionYear,
required this.primaryImage,
required this.primaryImageSmall,
required this.department,
required this.objectName,
required this.title,
required this.culture,
required this.period,
required this.artistPrefix,
required this.artistDisplayName,
required this.artistDisplayBio,
required this.medium,
required this.dimensions,
required this.geographyType,
required this.city,
required this.state,
required this.classification,
required this.linkResource,
required this.GalleryNumber});
static User fromJson(json) => User(
objectID: json['objectID'],
isHighlight: json['isHighlight'],
accessionYear: json['accessionYear'],
primaryImage: json['primaryImage'],
primaryImageSmall: json['primaryImageSmall'],
department: json['department'],
objectName: json['objectName'],
title: json['title'],
culture: json['culture'],
period: json['period'],
artistPrefix: json['artistPrefix'],
artistDisplayName: json['artistDisplayName'],
artistDisplayBio: json['artistDisplayBio'],
medium: json['medium'],
dimensions: json['dimensions'],
geographyType: json['geographyType'],
city: json['city'],
state: json['state'],
classification: json['classification'],
linkResource: json['linkResource'],
GalleryNumber: json['GalleryNumber']);
}
Now I'm having problems because the ListView is not created and gives me errors. Could you check the code and make sure everything is right?
I think the problem comes from the getUsers() class, where I try to get the API data.
In your user.dart file, you need a fromJson method but
it takes a map<String,dynamic> instead of a json
static User fromJson(Map<String, dynamic> json) => User(
objectID: json['objectID'],
isHighlight: json['isHighlight'],
accessionYear: json['accessionYear'],
primaryImage: json['primaryImage'],
primaryImageSmall: json['primaryImageSmall'],
department: json['department'],
objectName: json['objectName'],
title: json['title'],
culture: json['culture'],
period: json['period'],
artistPrefix: json['artistPrefix'],
artistDisplayName: json['artistDisplayName'],
artistDisplayBio: json['artistDisplayBio'],
medium: json['medium'],
dimensions: json['dimensions'],
geographyType: json['geographyType'],
city: json['city'],
state: json['state'],
classification: json['classification'],
linkResource: json['linkResource'],
GalleryNumber: json['GalleryNumber']);
}
And in your main file
You can create your instance of user like this :
static Future<List<User>> getUsers() async {
var body;
List<User> usersList = [];
for (int i = 1; i < 5; i++) {
String url =
'https://collectionapi.metmuseum.org/public/collection/v1/objects/$i';
var response = await http.get(Uri.parse(url));
body = json.decode(response.body);
usersList.add(User.fromJson(body));
}
return usersList;
}
and finally uncomment your code in the build method
Related
I have a problem with parsed JSON in Flutter-Dart. Actually, there is no problem, but there is a method which I don't know. I'm getting data from a PHP server and I'm writing to listview from parsed JSON. However, I don't want to write to a listview, I just want to get data from the parsed JSON because I will set an another textview from parsed json data which I get.
This is my code.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response =
await client.get(Uri.parse('https://meshcurrent.online/get_20word.php'));
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
class Photo {
final String questId;
final String quest;
final String ans1;
final String ans2;
final String ans3;
final String ans4;
final String correctAns;
final String category;
const Photo({
required this.questId,
required this.quest,
required this.ans1,
required this.ans2,
required this.ans3,
required this.ans4,
required this.correctAns,
required this.category,
});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
questId: json['questId'] as String,
quest: json['quest'] as String,
ans1: json['ans1'] as String,
ans2: json['ans2'] as String,
ans3: json['ans3'] as String,
ans4: json['ans4'] as String,
correctAns: json['correctAns'] as String,
category: json['category'] as String,
);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
const appTitle = 'Isolate Demo';
return const MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Column(children: [
Text("ronalddo"),
Text("mecsfsi"),
FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Center(
child: Text('An error has occurred!'),
);
} else if (snapshot.hasData) {
return PhotosList(photos: snapshot.data!);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
]));
}
}
class PhotosList extends StatelessWidget {
const PhotosList({Key? key, required this.photos}) : super(key: key);
final List<Photo> photos;
#override
Widget build(BuildContext context) {
return ListView.builder(
padding: EdgeInsets.all(20),
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: photos.length,
itemBuilder: (context, index) {
return ListTile(
title: Row(
children: [
Text(photos[index].quest),
Text(photos[index].ans1),
],
),
);
});
}
}
I want to do get only first column and get only questId from this parsed JSON. And I will set a textview using Getx library. I know set a data with Getx library but I can't do it because I don't know get the data.
If you just want to get the first questId of the List, do
photos[0].questId;
There is a flutter application that I wrote below. I'm trying to connect to mysql database and pull data with api, but every time I try, I get an error like the following. The model codes to which it is linked are also available below.
NoSuchMethodError (NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
Receiver: _LinkedHashMap len:3
Tried calling: cast<Map<String, dynamic>>()
Found: cast<Y0, Y1>() => Map<Y0, Y1>) I am getting this error. How can I fix.
import 'package:dbconnecttest/data.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: main1(),
);
}
}
class main1 extends StatefulWidget {
main1({Key? key}) : super(key: key);
#override
State<main1> createState() => _main1State();
}
class _main1State extends State<main1> {
Future<List<data>>? futuredata;
#override
void initState() {
// TODO: implement initState
futuredata = fetchPost();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Fake Friends"),
backgroundColor: Colors.green,
),
body: FutureBuilder<List<data>>(
future: futuredata,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (_, index) => Container(
child: Text("${snapshot.data![index].autid}"),
),
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
);
}
}
Future<List<data>> fetchPost() async {
final response =
await http.get(Uri.parse('http://192.168.1.108/server/data.php'));
if (response.statusCode == 200) {
final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
return parsed.map<data>((json) => data.fromJson(json)).toList();
} else {
throw Exception('Failed');
}
}
import 'dart:convert';
List<data> postFromJson(String str) =>
List<data>.from(json.decode(str).map((x) => data.fromJson(x)));
class data {
int? id;
String? autid;
String? status;
String? startdate;
String? finishdate;
data(
{required this.id,
required this.autid,
required this.status,
required this.startdate,
required this.finishdate});
data.fromJson(Map<String, dynamic> json) {
id = json['id'];
autid = json['autid'];
status = json['status'];
startdate = json['startdate'];
finishdate = json['finishdate'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['autid'] = this.autid;
data['status'] = this.status;
data['startdate'] = this.startdate;
data['finishdate'] = this.finishdate;
return data;
}
}
Try this
Map<String, dynamic>.from(data)
of course i can share. this is my flutter doctor
List posts=[];
Future getPost()async{
var url="https://jsonplaceholder.typicode.com/posts" ;
var http;
var response = await http.get(url);
var responsebody = jsonDecode(response.body) ;
return responsebody ;
// ignore: dead_code
setState(() {
posts.addAll(responsebody);
});
}
#override
void initState() {
getPost();
super.initState();
}
// ignore: dead_code
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:Text('Alex',style: TextStyle(color: Colors.cyanAccent),),
backgroundColor: Colors.black87,centerTitle: true,),
drawer: Drawer(),
body: posts == null || posts.isEmpty ? Center(child: CircularProgressIndicator(),) :
Center( child: ListView.builder(
itemCount : posts.length,
itemBuilder :(context,i){
return Text("${posts[i]['title']}");
}
,)
));
}}
Add this class
class MyClass {
final int userId;
final int id;
final String title;
final String body;
MyClass(
this.userId,
this.id,
this.title,
this.body);
factory MyClass.fromMap(Map<String, dynamic> json) {
return MyClass(
json['userId'],
json['id'],
json['title'],
json['body']);
}
}
then change getPost() method to :
import 'package:http/http.dart' as http;
Future getPost()async{
var url="https://jsonplaceholder.typicode.com/posts" ;
var response = await http.get(url);
final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
setState(() {
posts = parsed
.map<MyClass>((json) => MyClass.fromMap(json))
.toList();
});
}
The problem is with SDK tools. Open command prompt and run:
git clean -xfd
Restart your computer and then run:
flutter upgrade
I am trying o get data from newsApi but i seem to be getting the error above.
included is my main.dart code
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Article>> fetchArticles(http.Client client) async {
//final response = await client.get(Uri.parse('https://jsonplaceholder.typicode.com/Articles'));
String link = "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=MykEYhere";
final response = await client.get(Uri.parse(link));
// Use the compute function to run parseArticles in a separate isolate.
return compute(parseArticles, response.body);
}
// A function that converts a response body into a List<Article>.
List<Article> parseArticles(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Article>((json) => Article.fromJson(json)).toList();
}
class Article {
final String author;
final String title;
final String description;
final String url;
final String urlToImage;
final String content;
const Article({
required this.author,
required this.title,
required this.description,
required this.url,
required this.urlToImage,
required this.content
});
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
author: json['author'],
title: json['title'],
description: json['description'],
url: json['url'],
urlToImage: json['urlToImage'],
content: json['content'],
);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
const appTitle = 'NewApi Trial';
return const MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Article>>(
future: fetchArticles(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(
child: Text('An error has occurred! ${snapshot.error}'),
);
} else if (snapshot.hasData) {
return ArticlesList(articles: snapshot.data!);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
}
class ArticlesList extends StatelessWidget {
const ArticlesList({Key? key, required this.articles}) : super(key: key);
final List<Article> articles;
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: articles.length,
itemBuilder: (context, index) {
return ClipRect(
child: Column(
children: [
Image.network(articles[index].urlToImage),
Text(articles[index].title)
],
),
);
//Image.network(Articles[index].thumbnailUrl);
},
);
}
}
below is the Error im getting after running the code
NoSuchMethodError: Class'_InternalLinkedHashMap<String, dynamic>'has no instance method 'cast' with matching arguments. Reciever: _LinkedHashMap len:3 tried calling: cast<Map<String, dynamic>>() Founf: cast<RK, RV>()=>Map<RK, RV>
your assistance will be greatly appreciated
main.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'news_model.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: MyApp(),
));
}
// ignore: use_key_in_widget_constructors
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
NewsModel? newsmodel;
List<Articles>? articles;
Future<List<Articles>?> fetchNews() async {
final response = await http.get(Uri.parse(
"https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=YourAPIKEYHere"));
if (response.statusCode == 200) {
newsmodel = NewsModel.fromJson(jsonDecode(response.body));
setState(() {
articles = newsmodel!.articles;
});
return articles;
} else {
articles = null;
}
}
#override
void initState() {
fetchNews();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<Articles>?>(
future: fetchNews(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(
child: Text('An error has occurred! ${snapshot.error}'),
);
} else if (snapshot.hasData) {
return ArticlesList(articles: articles);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
}
class ArticlesList extends StatelessWidget {
const ArticlesList({Key? key, this.articles}) : super(key: key);
final List<Articles>? articles;
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: articles!.length,
itemBuilder: (context, index) {
return ClipRect(
child: Column(
children: [
Image.network(articles![index].urlToImage.toString()),
Text(articles![index].title.toString())
],
),
);
//Image.network(Articles[index].thumbnailUrl);
},
);
}
}
news_model.dart
class NewsModel {
String? status;
int? totalResults;
List<Articles>? articles;
NewsModel({this.status,this.totalResults,this.articles});
NewsModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
totalResults = json['totalResults'];
if (json['articles'] != null) {
articles = <Articles>[];
json['articles'].forEach((v) {
articles!.add(Articles.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['status'] = status;
data['totalResults'] = totalResults;
if (articles != null) {
data['articles'] = articles!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Articles {
Source? source;
String? author;
String? title;
String? description;
String? url;
String? urlToImage;
String? publishedAt;
String? content;
Articles(
{this.source,
this.author,
this.title,
this.description,
this.url,
this.urlToImage,
this.publishedAt,
this.content});
Articles.fromJson(Map<String, dynamic> json) {
source =
json['source'] != null ? Source.fromJson(json['source']) : null;
author = json['author'] ?? "Anonymous";
title = json['title'] ?? "Information Not Available";
description = json['description'] ?? "Description Not Available";
url = json['url'] ?? "https://i.imgur.com/8UdKNS4.jpg";
urlToImage = json['urlToImage'] ?? "https://i.imgur.com/8UdKNS4.jpg";
publishedAt = json['publishedAt'] ?? "Date Unavailable";
content = json['content'] ?? "Content Unavailable";
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
if (source != null) {
data['source'] = source!.toJson();
}
data['author'] = author;
data['title'] = title;
data['description'] = description;
data['url'] = url;
data['urlToImage'] = urlToImage;
data['publishedAt'] = publishedAt;
data['content'] = content;
return data;
}
}
class Source {
String? id;
String? name;
Source({this.id, this.name});
Source.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{} ;
data['id'] = id;
data['name'] = name;
return data;
}
}
Find the complete project here
I'm a very beginner at Flutter development, in the code below I tried to get data from here and display it in ListView :
static final String URL = "https://corona.lmao.ninja/countries";
Future<List<CoronaModel>> getData() async {
var data = await http.get(URL);
var jsonData = json.decode(data.body);
print("the count is: " + jsonData.toString()); //Data successfully printed
List<CoronaModel> listCoronaCountries = [];
for (var item in jsonData) {
CoronaModel mCorona = CoronaModel(
item["country"],
item["recovered"],
item["cases"],
item["critical"],
item["deaths"],
item["todayCases"],
item["todayDeaths"]);
listCoronaCountries.add(mCorona);
}
if (listCoronaCountries.length > 0) {
print("the count is: " + listCoronaCountries.length.toString());
} else {
print("EMPTY");
}
return listCoronaCountries;
}
At run time, the first print works, I can see the data successfully printed, but the IF statement is not showing
if (listCoronaCountries.length > 0) {
print("the count is: " + listCoronaCountries.length.toString());
} else {
print("EMPTY");
}
Model :
class CoronaModel {
final String country;
final String recovered;
final String cases;
final String critical;
final String deaths;
final String todayCases;
final String todayDeaths;
CoronaModel(this.country, this.recovered, this.cases, this.critical,
this.deaths, this.todayCases, this.todayDeaths);
}
You can copy paste run full code below
You can parse with coronaModelFromJson and display with FutureBuilder
code snippet
List<CoronaModel> coronaModelFromJson(String str) => List<CoronaModel>.from(
json.decode(str).map((x) => CoronaModel.fromJson(x)));
Future<List<CoronaModel>> getData() async {
var data = await http.get(URL);
List<CoronaModel> listCoronaCountries = coronaModelFromJson(data.body);
return listCoronaCountries;
}
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
// final coronaModel = coronaModelFromJson(jsonString);
import 'dart:convert';
List<CoronaModel> coronaModelFromJson(String str) => List<CoronaModel>.from(
json.decode(str).map((x) => CoronaModel.fromJson(x)));
String coronaModelToJson(List<CoronaModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CoronaModel {
String country;
int cases;
int todayCases;
int deaths;
int todayDeaths;
int recovered;
int active;
int critical;
int casesPerOneMillion;
CoronaModel({
this.country,
this.cases,
this.todayCases,
this.deaths,
this.todayDeaths,
this.recovered,
this.active,
this.critical,
this.casesPerOneMillion,
});
factory CoronaModel.fromJson(Map<String, dynamic> json) => CoronaModel(
country: json["country"],
cases: json["cases"],
todayCases: json["todayCases"],
deaths: json["deaths"],
todayDeaths: json["todayDeaths"],
recovered: json["recovered"],
active: json["active"],
critical: json["critical"],
casesPerOneMillion: json["casesPerOneMillion"],
);
Map<String, dynamic> toJson() => {
"country": country,
"cases": cases,
"todayCases": todayCases,
"deaths": deaths,
"todayDeaths": todayDeaths,
"recovered": recovered,
"active": active,
"critical": critical,
"casesPerOneMillion": casesPerOneMillion,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static final String URL = "https://corona.lmao.ninja/countries";
Future _future;
Future<List<CoronaModel>> getData() async {
var data = await http.get(URL);
List<CoronaModel> listCoronaCountries = coronaModelFromJson(data.body);
return listCoronaCountries;
}
#override
void initState() {
// TODO: implement initState
super.initState();
_future = getData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder<List<CoronaModel>>(
future: _future,
builder: (BuildContext context,
AsyncSnapshot<List<CoronaModel>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Input a URL to start');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
' ${snapshot.data[index].country} , ${snapshot.data[index].cases}'),
);
});
}
}
}));
}
}
Instead of hand coding '.fromJson/.toJson' methods. you could rely on
this library https://github.com/k-paxian/dart-json-mapper,
It will help you not only for this case, but for all Dart Object => JSON => Dart Object cases.