我正在try 从API获取数据.但它显示以下错误. 我怎么才能解决这个问题呢?

未处理的异常:第1行第5列的错误:无效的媒体类型:应为"/"

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),
            )
          ],
        ),
      );
    }
    );
  }
}

推荐答案

Web服务器返回Content-Type设置为json的响应.这是一个问题,因为您的客户希望它是application/json.

  1. 如果您控制了Web服务器

    • 考虑将响应头修改为application/json.根据IANA standards的说法,这将是正确的 Select
  2. 如果您无法控制Web服务器

    • 不要使用response.body,代之以utf8.decode(response.bodyBytes);.这是http包的一种解决方法,可阻止其try 使用无效内容类型.这一点也将在this github issue

Flutter相关问答推荐

当仅点击一行时,所有行都被选中

在创建肘部并使用冻结时,无法使用中的Copy With方法

Flutter /dart 列表.第一个子类列表中的Where()错误

从.gitignore中排除.fvm/fvm_config.json

如果我使用搜索栏,如何在嵌套滚动视图中停止自动滚动?

顶部对齐ListTile的[前导、标题、尾随]小部件

如何使 dart 函数变得通用?

如何在 Flutter 中创建厚度沿着容器逐渐减小的边框

在使用 Android 12+ 的真实 Android 设备上,SingleChildScrollView 中最初位于视口之外的无响应 Web 视图

更改底部导航栏下方 Flutter Snackbar 的位置

使用 riverpod 提供 GoRouter 实例的正确方法是什么?

如何使用 riverpod_annotation 创建非自动处置提供程序?

Flutter ListView 在 Column 中工作但在 Row 中不工作

flutter 创建一个带有 2 个图标的按钮

如何在图像上点或(图像的一部分)在 flutter 中点击?

将一个 Flutter 应用程序集成到另一个 Flutter 应用程序中

我一直在try 创建按钮以导航到第二页,但不知何故 RaisedButton 功能无法正常工作

运行Flutter 测试时出现 FirebaseAppPlatform.verifyExtends 错误

解密 Modulr 安全令牌

如何从 Firebase Firestore 中获取具有特定字段值的文档?