skip to Main Content

I was practicing this covid-19 tracker application using flutter from a tutorial on YouTube, so after writing a few code when I hit the API and run the application, it throws this exception, I don’t understand why as I am a beginner and a newbie on Flutter.

import 'dart:convert';

import 'package:covid_tracker/Model/world_states_model.dart';
import 'package:http/http.dart' as http;

import 'Utilities/app_url.dart';

class StatesServices {
// async means waiting for your request

  Future<WorldStatesModel> fetchWorldStatesRecords() async {
    final response = await http.get(Uri.parse(AppUrl.worldStatesApi));

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body);
      return WorldStatesModel.fromJson(data);
    } else {
      throw Exception('Error');
    }
  }
}

class AppUrl {
// this is our base url
  static const String baseUrl = 'https://disease.sh/v3/covid-19';

// fetch world covid states
  static const String worldStatesApi = '${baseUrl}all';
  static const String countriesList = '${baseUrl}countries';
}

Exception thrown

2

Answers


  1. You are getting a status code that’s not 200. Therefore your application throws an error, just as you have programmed it!

    The first step would be to actually figure out why you are getting a different status code from 200. Looking at your code it seems that you try to visit '${baseUrl}all'. This translates to https://disease.sh/v3/covid-19all. This URL however does not exist.

    To fix your issue try adding a / after ${baseUrl}. Such that it becomes '${baseUrl}/all'. Or add the change the baseUrl variable to https://disease.sh/v3/covid-19/. After that, your error should be resolved.

    I recommend printing to the console what links you are trying to load. It would probably prevent this kind of issue in the future. Or even more useful, include it in the exception you throw. 🙂

    Login or Signup to reply.
  2. if stataus !=200 from API,
    You are throwing exception in this line

     throw Exception('Error');
    

    it shows API is not returning the needed data.

    Try to change line

    static const String baseUrl = 'https://disease.sh/v3/covid-19';
    

    to

    static const String baseUrl = 'https://disease.sh/v3/covid-19/';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search