参数类型 'Future<List<dynamic>>' 无法分配给参数类型 'Future<List<ModelClass>>?'

The argument type 'Future<List<dynamic>>' can't be assigned to the parameter type 'Future<List<ModelClass>>?'

我遇到了这个错误

我似乎不明白我做错了什么,请帮忙。

我正在休息取数据api

代码如下:

FutureBuilder<List<Articles>>(
          future: fetchApiData(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return ListView.separated(
                itemBuilder: (context, index) {
                  Articles articles = snapshot.data![index];
                  const SizedBox(height: 150,);
                  return Container(
                    padding: const EdgeInsets.all(10),
                    foregroundDecoration: BoxDecoration(
                      border: Border.all(
                        color: golden,
                        width: 2,
                      ),
                      borderRadius: BorderRadius.circular(5),
                    ),
                    width: 180,
                    height: 139,
                    margin: const EdgeInsets.all(5),
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: NetworkImage(articles.urlToImage!),
                        fit: BoxFit.fill,
                      ),
                    ),
                  );
                },
                itemCount: snapshot.data!.length, separatorBuilder: (BuildContext context, int index) {
                return const SizedBox(height: 10,);
              },
              );
            } else if (snapshot.hasError) {
              return Text('${snapshot.error}');
            }
            return const CircularProgressIndicator();
          },
        ),
          Future<List> fetchApiData() async {
    final response = await http
        .get(Uri.parse('https://newsapi.org/v2/top-headlines?country=us&apiKey=dee40e91ae644e9d818dd88498534c71'));

    if (response.statusCode == 200) {
      List<dynamic> list = convert.jsonDecode(response.body);

      List apiData =
      list.map((e) => Articles.fromJson(e)).toList();

      return apiData;
    } else {
      throw Exception('Failed to load data');
    }
  }

我是编程新手,flutter一般

api的响应没问题 我测试过了 使用postman测试结果

因为你的 fetchApiData 函数 return List<dynamic> 将来类型,flutter 无法知道 dynamic 类型是 Articles 类型,所以将你的 fetchApiData 更改为:

  Future<List<Articles>> fetchApiData() async {
    final response = await http
        .get(Uri.parse('https://newsapi.org/v2/top-headlines?country=us&apiKey=dee40e91ae644e9d818dd88498534c71'));

    if (response.statusCode == 200) {
      List<dynamic> list = convert.jsonDecode(response.body);

      List<Articles> apiData =
      list.map((e) => Articles.fromJson(e)).toList();

      return apiData;
    } else {
      throw Exception('Failed to load data');
    }
  }