flutterdarthttp

Getting an error when requesting data from http


I don't know what I need to do, I tried to change my URL. But I am still getting this error.

Here is the error.

Exception has occurred.
FormatException (FormatException: Unexpected character (at character 1)
<!DOCTYPE html>
^
)

Below is the code where I request the data

    Map<dynamic, dynamic> venuesData;

  Future<void> fetchAndSetVenues() async {
    try {
      final response = await http.get(Uri.parse(venuesURL));
      final extractedData = json.decode(response.body) as Map<dynamic, dynamic>;
      venuesData = extractedData;
      print(venuesData);
    } catch (error) {
      throw error;
    }
  }

  // events
  Map<dynamic, dynamic> eventsData;

  Future<void> fetchAndSetEvents() async {
    try {
      final response = await http.get(Uri.parse(eventsURL));
      final extractedData = json.decode(response.body) as Map<dynamic, dynamic>;
      eventsData = extractedData;
    } catch (error) {
      throw error;
    }
  }

And here are my URLs

String eventsURL = 'http://medeni.art/api/v1/events?page=1'

String venuesURL = 'http://medeni.art/api/v1/venues'

Solution

  • This error occurs in json.decode method. For any reason, if http request get error, the json.decode should not be called. You can check request response status code.

    import 'package:http/http.dart' as http;
    
    var url = Uri.parse('https://example.com/whatsit/create');
    var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
    if(response.statusCode ==200){
      final result = json.decode(response.body);
    }