flutterdart

Unhandled Exception: Error on line 1, column 5: Invalid media type: expected "/". in Flutter when fetching data from an API


I am trying to fetch data from an API. But it show the following error. How can I solve the problem.

Unhandled Exception: Error on line 1, column 5: Invalid media type: expected "/"

Category model Class:

class Category {
  final int id;
  final String name;

  Category({required this.id, required this.name});

  factory Category.fromJson(Map<String, dynamic> json) {
    return Category(
      id: json['id'],
      name: json['name'],
    );
  }
}

Class for Fetch data

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

import '../models/category.dart';


class CategoryList extends StatefulWidget{
  const CategoryList({super.key});

  @override
  State<CategoryList> createState() => _CategoryListState ();
}

class _CategoryListState extends State<CategoryList> {
  List<dynamic> data=[];
  Future<List<Category>> fetchData() async {
    final response = await http.get(Uri.parse('https://stackvaly.com/questionbankappsapi/datafetch.php')
     , headers: {"Accept": "application/json"},);

    if (response.statusCode == 200) {
      data = json.decode(response.body);
      return data.map((json) => Category.fromJson(json)).toList();
    } else {
      throw Exception('Failed to load data from API');
    }
  }
  @override
  void initState() {
    fetchData();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: data.length,
        itemBuilder: (context,index)
    {
      return Container(
        padding: const EdgeInsets.all(12.0),
        decoration: BoxDecoration(
          color: const Color.fromARGB(95, 179, 173, 173),
          borderRadius: BorderRadius.circular(15.0),
        ),
        child: Row(
          children: [
            Text(
              data[index]['name'],
              style: const TextStyle(fontSize: 14),
            ),
             const SizedBox(
              width: 8,
            ),
            Text(
              data[index]['name'],
              style: const TextStyle(fontSize: 14),
            )
          ],
        ),
      );
    }
    );
  }
}

Solution

  • The webserver returns a response with Content-Type set to json. This is a problem since your client expects it to be application/json instead.

    1. If you are in control of the web server

      • consider modifying the response header to application/json. This would be the correct choice according to IANA standards
    2. If you are not in control of the webserver

      • Do not use response.body and replace it with utf8.decode(response.bodyBytes); instead. This is a workaround for the http package to stop it from trying to use the invalid content type. This is also being discussed in this github issue