Home > front end >  Can anyone explain the function of .map()
Can anyone explain the function of .map()

Time:09-26

I was trying to make a Covid Tracking application using flutter, and I came across this 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

List<CountrySummaryModel> summaryList = (json.decode(data.body) as List).map((item) => CountrySummaryModel.fromJson(item)).toList();

is trying to do, and CountrySummaryModel is an 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"],
    );
  }
}

CodePudding user response:

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.

CodePudding user response:

If I understand your code correctly:

  1. First, you convert data to List.

  2. Then, use CountrySummaryModel.fromJson() and .toList() to convert it to List<CountrySummaryModel>.

  • Related