You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter调用News API遇_TypeError类型不匹配,求解决方案

解决Flutter调用News API时的_TypeError错误

错误根源分析

  1. API数据解析逻辑错误:News API返回的JSON结构外层包含status、totalResults和articles数组,你直接对整个JSON对象调用map方法——而map是Map类型的方法,要求传入(String, dynamic) => MapEntry类型的转换函数,但你传入的是生成Article对象的函数,导致类型不匹配。
  2. 冗余代码引发参数错误:Article类中定义了无意义的article getter,在HomePage传递ChamadaSuite参数时错误传入article.article(实际传递了null);同时ChamadaSuite组件重复定义了Article的字段参数,造成冗余和潜在错误。

修复步骤

1. 修正API数据解析逻辑

修改getArticle函数,正确提取articles数组后再转换为Article列表:

Future<List<Article>> getArticle() async {
  final response = await http.get(Uri.parse(url));
  if (response.statusCode == 200) {
    var data = jsonDecode(response.body);
    // 提取API返回的articles数组
    List<dynamic> articlesJson = data['articles'];
    List<Article> articles =
        articlesJson.map((json) => Article.fromJson(json)).toList();
    print(articles);
    return articles;
  } else {
    throw Exception("Failed to get articles");
  }
}

2. 清理Article模型冗余代码

删除无用的article getter,并增加空值处理避免API返回null时初始化失败:

class Article {
  final String title;
  final String author;
  final String description;
  final String url;
  final String urlToImage;
  final String content;

  const Article({
    required this.title,
    required this.author,
    required this.description,
    required this.url,
    required this.urlToImage,
    required this.content,
  });

  factory Article.fromJson(Map<String, dynamic> json) {
    return Article(
      title: json['title'] ?? '',
      author: json['author'] ?? '',
      description: json['description'] ?? '',
      url: json['url'] ?? '',
      urlToImage: json['urlToImage'] ?? '',
      content: json['content'] ?? '',
    );
  }

  // 移除下面这行冗余代码
  // get article => null;
}

3. 简化ChamadaSuite组件参数

删除重复的字段参数,仅保留Article对象,并优化图片加载逻辑:

class ChamadaSuite extends StatelessWidget {
  final Article article;

  const ChamadaSuite({
    super.key,
    required this.article,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(20),
      child: Row(
        children: [
          Container(
            width: 110,
            height: 90,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              image: DecorationImage(
                fit: BoxFit.cover,
                image: article.urlToImage.isNotEmpty
                    ? NetworkImage(article.urlToImage)
                    : const AssetImage("assets/vasco.png") as ImageProvider,
              ),
            ),
          ),
          Flexible(
            child: Container(
              padding: const EdgeInsets.only(left: 15),
              width: MediaQuery.of(context).size.width,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    "ESPORTE",
                    style: TextStyle(
                      color: Colors.green,
                      fontSize: 12,
                      fontWeight: FontWeight.w500,
                      height: 1.2,
                      letterSpacing: 0.13,
                    ),
                  ),
                  Text(
                    article.title,
                    style: const TextStyle(
                      color: Colors.black,
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      height: 1.4,
                      letterSpacing: 0.16,
                    ),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

4. 修正HomePage传参逻辑

移除冗余字段参数,仅传递Article对象,同时删除嵌套的SingleChildScrollView避免滚动冲突:

// ... 其他代码不变
return ListView.builder(
    itemCount: snapshot.data!.length,
    itemBuilder: (context, index) {
      Article article = snapshot.data![index];
      return Column(
        children: [
          const MancheteSuiteDestaque(),
          ChamadaSuite(
            article: article,
          ),
        ],
      );
    });
// ...

内容的提问来源于stack exchange,提问作者Yan Cordeiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 11:05:15