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

使用newsapi.org开发新闻App遇Dart非空类型错误求助

问题分析与解决

你的错误根源是:getArticle()方法中,当请求成功(statusCode == 200)时,你创建了articles列表,但没有将它返回。虽然你在else分支里抛出了异常,但if分支执行完毕后没有返回值,Dart会认为方法可能返回null,而你声明的返回类型Future<List<Article>>是不可空类型,因此触发了这个错误。

修正后的代码

import 'dart:convert';
import 'package:http/http.dart';
import 'package:medreminder/NewsArticle/models/article_models.dart';

class ApiService {
  final endPointUrl = 
      "https://newsapi.org/v2/top-headlines?country=us&apiKey=cacee27fff544eb39d5fb29b28ca3788"; 

  Future<List<Article>> getArticle() async {
    Response res = await get(Uri.parse(endPointUrl));

    if(res.statusCode == 200) {
      Map<String, dynamic> json = jsonDecode(res.body);
      List<dynamic> body = json['articles'];
      List<Article> articles = 
          body.map((dynamic item) => Article.fromJson(item)).toList();
      // 新增return语句,返回articles列表
      return articles;
    } else {
      throw("Cant get the News");
    }
  }
}

只要在if代码块末尾添加return articles;,让方法在请求成功时返回正确的列表,错误就会消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:50:30