为什么我的应用在调用冠状病毒 API 时会抛出错误?

Why my app throw error when i call the coronavirus API?

我正在为我的 class 构建一个关于冠状病毒追踪器的项目。每次我尝试调用 api 并点击搜索图标时,它都会在控制台中抛出错误。我尝试了很多东西,但它抛出了同样的错误。任何人都可以帮助找出代码有什么问题吗?

    class _HomePageState extends State<HomePage> {
      List <Data> data = [];
      var countryController = TextEditingController();
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Center(child: Text('CoronaVirus Tracker')),
            ),
    
            body: Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Expanded(
                      child: TextField(
                        decoration: InputDecoration(
                            border: InputBorder.none, hintText: 'Enter a Country'),
                        controller: countryController,
                      ),
                    ),
    
                    IconButton(
                        icon: Icon(Icons.search),
                        color: Colors.blue,
                        onPressed: () {
                          fetchData().then((newData) {
                            setState(() {
                              data = newData as List<Data>;
                            });
                          });
                        }),
                  ],
                ),
    
                 //The search item appear here
                Expanded(
                  child: ListView.builder(
                    itemBuilder: (BuildContext context, int index) {
                      return Card(
                        child: ListTile(
                          title: Text(data[index].country),
                          subtitle: Text(data[index].cases),
                          onTap: () => {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) =>
                                        Text('This is a new page!!')))
                          },
                        ),
                      );
                    },
                    itemCount: data.length,
                  ),
                ),
              ],
            ));
      }
    

这是Api代码

      Future <Data> fetchData() async {
        final response = await http.get('https://api.covid19api.com/live/country/malaysia/status/confirmed');
        if (response.statusCode == 200) {
          print(response.body);
          // Transform json into object
          return Data.fromJson(json.decode(response.body));
        } else {
          // If the server did not return a 200 OK response,
          // then throw an exception.
          throw Exception('Failed to load data');
        }
      }
    }
    

这里是构造函数

    class Data {
      final String date;
      final String country;
      final String cases;
    
      Data({this.date, this.country, this.cases});

      factory Data.fromJson(Map<String, dynamic> json) {
        return Data(
            country: json['Country'],
            date: json['Date'],
            cases: json['Cases']);
      }
    }

根据上面提到的代码,我为您创建了一个示例。

import 'dart:convert';

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isLoading = false;
  List<Data> data = List();
  TextEditingController countryController = TextEditingController();

  Future<List<Data>> fetchData(String countryName) async {
    setState(() {
      _isLoading = true;
    });

    //https://api.covid19api.com/live/country/india/status/confirmed
    final response = await http.get(
        'https://api.covid19api.com/live/country/$countryName/status/confirmed');
    print(response.statusCode);
    if (response.statusCode == 200) {
      print(response.body);
      // Transform json into object

      var items = json.decode(response.body);

      items.forEach((item) {
        data.add(Data.fromJson(item));
      });
      return data;
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load data');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Center(child: Text('CoronaVirus Tracker')),
          ),
          body: Column(
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: TextField(
                        decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: 'Enter a Country'),
                        controller: countryController,
                      ),
                    ),
                    IconButton(
                        icon: Icon(Icons.search),
                        color: Colors.blue,
                        onPressed: () {
                          fetchData(countryController.text).then((newData) {
                            setState(() {
                              data = newData;
                              _isLoading = false;
                            });
                          });
                        }),
                  ],
                ),
              ),
              _isLoading
                  ? CircularProgressIndicator()
                  :
                  //The search item appear here
                  Expanded(
                      child: ListView.builder(
                        itemBuilder: (BuildContext context, int index) {
                          return Card(
                            child: ListTile(
                              title: Text(data[index].date.toString()),
                              subtitle: Text(data[index].cases.toString()),
                              onTap: () {
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            Text('This is a new page!!')));
                              },
                            ),
                          );
                        },
                        itemCount: data.length,
                      ),
                    ),
            ],
          )),
    );
  }
}

class Data {
  final String date;
  final String country;
  final int cases;

  Data({this.date, this.country, this.cases});

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
        country: json['Country'], date: json['Date'], cases: json['Active']);
  }
}

根据需要更改模型 class 参数。

请查看并告诉我它是否有效。