My Code Return [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'String' is not a subtype of type 'int'

2703 views flutter flutter-layout
13

Somehow my code return this error everytime i call the api.

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'String' is not a subtype of type 'int'

Yesterday it was fine. My Api call always come out. Now that message always come out whenever i call the api. Here is my code

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool _isLoading = false;
  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(countryController.text).then((newData) {
                        setState(() {
                          data = newData;
                          _isLoading = false;
                        });
                      });
                    }),
              ],
            ),

            _isLoading ? CircularProgressIndicator()
            :
            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) =>
                                 Information()))
                      },
                    ),
                  );
                },
                itemCount: data.length,
              ),
            ),
          ],
        ));
  }
}

Here is the future.

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

    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
      json.decode(response.body).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');
    }
  }

The Class Constructor

class Data {
  final int 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['Confirmed']);
  }
}

I have tried many things but nothing work so far on my end. Can some help me out here? I really stuck right now.

answered question

3 Answers

5

I think there is some problem with the response of API. So once try to change your class constructor code as below. I hope it will help you.

 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['Confirmed']);
 }
}

posted this
9

I don't know if the api you're using changed its format but now date is of type String

[
  {
    "Country": "Malaysia",
    "CountryCode": "MY",
    "Province": "",
    "City": "",
    "CityCode": "",
    "Lat": "4.21",
    "Lon": "101.98",
    "Confirmed": 4683,
    "Deaths": 76,
    "Recovered": 2108,
    "Active": 2499,
    "Date": "2020-04-13T00:00:00Z" //Is a String now
  },
...

So you will have to update your model parameter to a String

final String date;

posted this
3

The issue is caused by the date field in Data Modal, value returned from API is String and the type described in the Data modal is int, thus causing an typecast issue, update your data model as following -

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['Confirmed']);
  }
}

Hope this helps!

posted this

Have an answer?

JD

Please login first before posting an answer.