[英]Can anyone explain the function of .map()
I was trying to make a Covid Tracking application using flutter, and I came across this function getCountrySummary( ) ,我试图使用 flutter 制作 Covid Tracking 应用程序,我遇到了这个 function getCountrySummary() ,
import 'package:covid_tracker/models/country_summary.dart';
import 'package:covid_tracker/models/global_summary.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class CovidService {
Future<GlobalSummaryModel> getGlobalSummary() async {
final data =
await http.get(Uri.parse('https://api.covid19api.com/summary'));
if (data.statusCode != 200) {
throw Exception();
}
GlobalSummaryModel summary =
GlobalSummaryModel.fromJson(json.decode(data.body));
return summary;
}
Future<List<CountrySummaryModel>> getCountrySummary(String slug) async {
String url = "https://api.covid19api.com/total/dayone/country/$slug";
final data = await http.get(Uri.parse(url));
if (data.statusCode != 200) {
throw Exception();
}
List<CountrySummaryModel> summaryList = (json.decode(data.body) as List)
.map((item) => CountrySummaryModel.fromJson(item))
.toList();
return summaryList;
}
}
So I know what the function getCountrySummary() is trying to do, but I don't understand what statement所以我知道 function getCountrySummary() 试图做什么,但我不明白什么说法
List<CountrySummaryModel> summaryList = (json.decode(data.body) as List).map((item) => CountrySummaryModel.fromJson(item)).toList();
is trying to do, and CountrySummaryModel is an object.正在尝试做,而 CountrySummaryModel 是 object。
class CountrySummaryModel {
final String country;
final int confirmed;
final int death;
final int recovered;
final int active;
final DateTime date;
CountrySummaryModel(this.country, this.active, this.confirmed, this.date,
this.death, this.recovered);
factory CountrySummaryModel.fromJson(Map<String, dynamic> json) {
return CountrySummaryModel(
json["country"],
json["active"],
json["confirmed"],
DateTime.parse(json["date"]),
json["death"],
json["recovered"],
);
}
}
When you call Map
on a list, it means you want to reach each item in it, in your case you call map on your list to parse each item in it and at then call toList()
to make a list of this items.当您在列表上调用
Map
时,这意味着您想要访问其中的每个项目,在您的情况下,您在列表中调用 map 以解析其中的每个项目,然后调用toList()
来制作这些项目的列表。
If I understand your code correctly:如果我正确理解您的代码:
First, you convert data
to List
.首先,将
data
转换为List
。
Then, use CountrySummaryModel.fromJson()
and .toList()
to convert it to List<CountrySummaryModel>
.然后,使用 CountrySummaryModel.fromJson(
CountrySummaryModel.fromJson()
和.toList()
将其转换为List<CountrySummaryModel>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.