'_InternalLinkedHashMap <String,dynamic>'没有实例方法'cast'具有匹配的参数

时间:2020-09-01 00:21:49

标签: flutter dart

每次运行...

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:rona/Models/Global_model.dart';

class NetworkHelper {
  static const String url = 'https://covid-193.p.rapidapi.com/statistics';

  static List<GlobalDataModel> parse(String responseBody) {
    final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    return parsed
        .map<GlobalDataModel>((json) => GlobalDataModel.fromMap(json))
        .toList();
  }

  static Future<List<GlobalDataModel>> getGlobalData() async {
    try {
      final response = await http.get(url, headers: {
        "x-rapidapi-host": "covid-193.p.rapidapi.com",
        "x-rapidapi-key": "1d2e200e8amsh264b6230392cdfcp119d06jsn3f9a7a0e8fd0",
        "useQueryString": "true"
      });
      if (response.statusCode == 200) {
        List<GlobalDataModel> list = parse(response.body);
        return list;
      } else {
        throw Exception("Error");
      }
    } catch (e) {
      throw Exception(e.toString());
    }
  }
}

我收到以下错误。我看过其他人遇到的其他类似问题,但似乎没有一个起作用。

E/flutter (26845): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: Exception: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
E/flutter (26845): Receiver: _LinkedHashMap len:5
E/flutter (26845): Tried calling: cast<Map<String, dynamic>>()
E/flutter (26845): Found: cast<RK, RV>() => Map<RK, RV>

我相应的模型文件如下所示...

import 'package:rona/Networking/Global_data.dart';

class GlobalDataModel {
  String continent;
  String country;
  int population;
  int activeCases;
  int criticalCases;
  int totalCases;
  int recovered;
  int totalDeaths;

  GlobalDataModel({
    this.continent,
    this.country,
    this.population,
    this.activeCases,
    this.criticalCases,
    this.recovered,
    this.totalCases,
    this.totalDeaths,
  });

  Future<dynamic> getGlobalData() async {
    await NetworkHelper.getGlobalData().then((data) {
      print('Data: ${data.length}');
    });
  }

  factory GlobalDataModel.fromMap(Map<String, dynamic> map) {
    return GlobalDataModel(
      continent: map['response']['continent'] as String,
      country: map['response']['country'] as String,
      population: map['response']['population'] as int,
      activeCases: map['reponse']['cases']['active'] as int,
      criticalCases: map['response']['cases']['critical'] as int,
      recovered: map['response']['cases']['recovered'] as int,
      totalCases: map['response']['cases']['total'] as int,
      totalDeaths: map['response']['deaths']['total'] as int,
    );
  }
}

而json看起来像这样...

{
  "get": "statistics",
  "parameters": [],
  "errors": [],
  "results": 227,
  "response": [
    {
      "continent": "Asia",
      "country": "China",
      "population": 1439323776,
      "cases": {
        "new": "+9",
        "active": 244,
        "critical": 5,
        "recovered": 80153,
        "1M_pop": "59",
        "total": 85031
      },
      "deaths": {
        "new": null,
        "1M_pop": "3",
        "total": 4634
      },
      "tests": {
        "1M_pop": "62814",
        "total": 90410000
      },
      "day": "2020-08-30",
      "time": "2020-08-30T17:00:11+00:00"
    },
    {
      "continent": "Europe",
      "country": "Italy",
      "population": 60447003,
      "cases": {
        "new": "+1365",
        "active": 24205,
        "critical": 86,
        "recovered": 208536,
        "1M_pop": "4437",
        "total": 268218
      },
      "deaths": {
        "new": "+4",
        "1M_pop": "587",
        "total": 35477
      },
      "tests": {
        "1M_pop": "142130",
        "total": 8591341
      },
      "day": "2020-08-30",
      "time": "2020-08-30T17:00:11+00:00"
    },
    {
      "continent": "Europe",
      "country": "Spain",
      "population": 46757684,
      "cases": {
        "new": "+3829",
        "active": 0,
        "critical": 751,
        "recovered": 0,
        "1M_pop": "9744",
        "total": 455621
      },
      "deaths": {
        "new": "+15",
        "1M_pop": "620",
        "total": 29011
      },
      "tests": {
        "1M_pop": "182161",
        "total": 8517446
      },
      "day": "2020-08-30",
      "time": "2020-08-30T17:00:11+00:00"
    }]

请帮帮我,我已经花了一段时间了。

虚拟文本虚拟文本文本虚拟文本虚拟文本虚拟文本

2 个答案:

答案 0 :(得分:1)

您为cast错误地提供了类型参数。您为它提供所需键和值的类型实参,而不是Map本身:

final parsed = json.decode(responseBody).cast<String, dynamic>();

但是,对于转换后的JSON字符串,通常仅使用as运算符进行常规转换是安全的:

final parsed = json.decode(responseBody) as Map<String, dynamic>;

或通过为parsed提供显式类型来隐式转换:

final Map<String, dynamic> parsed = json.decode(responseBody);

答案 1 :(得分:0)

您可以在下面复制粘贴运行完整代码
要返回List<GlobalDataModel>,可以使用List<GlobalDataModel>.from( parsed["response"]
代码段

static List<GlobalDataModel> parse(String responseBody) {
    final Map<String, dynamic> parsed = json.decode(responseBody);

    return List<GlobalDataModel>.from(
        parsed["response"].map((x) => GlobalDataModel.fromJson(x)));
  }
...  
factory GlobalDataModel.fromJson(Map<String, dynamic> map) {
    return GlobalDataModel(
      continent: map['continent'] as String,
      country: map['country'] as String,
      population: map['population'] as int,
      activeCases: map['cases']['active'] as int,
      criticalCases: map['cases']['critical'] as int,
      recovered: map['cases']['recovered'] as int,
      totalCases: map['cases']['total'] as int,
      totalDeaths: map['deaths']['total'] as int,
    );

工作演示

enter image description here

完整代码

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

class NetworkHelper {
  static const String url = 'https://covid-193.p.rapidapi.com/statistics';

  static List<GlobalDataModel> parse(String responseBody) {
    final Map<String, dynamic> parsed = json.decode(responseBody);

    return List<GlobalDataModel>.from(
        parsed["response"].map((x) => GlobalDataModel.fromJson(x)));
  }

  static Future<List<GlobalDataModel>> getGlobalData() async {
    try {
      final response = await http.get(url, headers: {
        "x-rapidapi-host": "covid-193.p.rapidapi.com",
        "x-rapidapi-key": "1d2e200e8amsh264b6230392cdfcp119d06jsn3f9a7a0e8fd0",
        "useQueryString": "true"
      });
      if (response.statusCode == 200) {
        print(response.body);
        List<GlobalDataModel> list = parse(response.body);
        return list;
      } else {
        throw Exception("Error");
      }
    } catch (e) {
      throw Exception(e.toString());
    }
  }
}

class GlobalDataModel {
  String continent;
  String country;
  int population;
  int activeCases;
  int criticalCases;
  int totalCases;
  int recovered;
  int totalDeaths;

  GlobalDataModel({
    this.continent,
    this.country,
    this.population,
    this.activeCases,
    this.criticalCases,
    this.recovered,
    this.totalCases,
    this.totalDeaths,
  });

  Future<dynamic> getGlobalData() async {
    await NetworkHelper.getGlobalData().then((data) {
      print('Data: ${data.length}');
    });
  }

  factory GlobalDataModel.fromJson(Map<String, dynamic> map) {
    return GlobalDataModel(
      continent: map['continent'] as String,
      country: map['country'] as String,
      population: map['population'] as int,
      activeCases: map['cases']['active'] as int,
      criticalCases: map['cases']['critical'] as int,
      recovered: map['cases']['recovered'] as int,
      totalCases: map['cases']['total'] as int,
      totalDeaths: map['deaths']['total'] as int,
    );
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      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> {
  Future<List<GlobalDataModel>> _future;

  @override
  void initState() {
    _future = NetworkHelper.getGlobalData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<List<GlobalDataModel>> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                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 Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data[index].country
                                        .toString()),
                                    Spacer(),
                                    Text(snapshot.data[index].totalCases
                                        .toString()),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}