【问题标题】:A value of type 'List<News>?' can't be assigned to a variable of type 'List<News>''List<News>?' 类型的值不能分配给“List<News>”类型的变量
【发布时间】:2021-12-08 00:51:26
【问题描述】:
Future<List<News>> getNews() async {
  final Url =
      "https://api.stockdata.org/v1/news/all?symbols=&filter_entities=true&language=en&api_token=api_token&countries=";
  final response = await http.get(Uri.parse(Url));
  if (response.statusCode == 200) {
    List jsonResponse = json.decode(response.body);
    return jsonResponse.map((data) => News.fromJSON(data)).toList();
  } else {
    throw Exception("Unexpected error occurred!");
  }
}
class News {
  final String title;
  final String desc;
  final String imgURL;
  final String url;

  News(
      {required this.title,
      required this.desc,
      required this.imgURL,
      required this.url});

  factory News.fromJSON(Map<String, dynamic> json) {
    return News(
        title: json["title"],
        desc: json["description"],
        imgURL: json["image_url"],
        url: json["url"]);
  }
}
FutureBuilder<List<News>>(
              future: futureNews,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  List<News> data = snapshot.data;      -----> Error
                  return ListView.builder(),              

我正在尝试使用 Stockdata API 为股票构建一个新闻小部件,它以 JSON 格式发送数据,但我不断收到错误消息:

A value of type 'List<News>?' can't be assigned to a variable of type 'List<News>'. 

错误发生在List data = snapshot.data;

谁能帮帮我吗?

【问题讨论】:

  • 哪一行显示错误?
  • 列表 data = snapshot.data;行

标签: json flutter dart


【解决方案1】:

您可以尝试更新List&lt;News&gt; data = snapshot.requireData; 吗?

【讨论】:

  • 这确实解决了我的错误,但现在我遇到了一个新错误:')
  • type '_InternalLinkedHashMap' 不是类型 'List' 的子类型
  • 我觉得List jsonResponse = json.decode(response.body);这个错误你可以试试cast:json.decode(response.body) as List ?
  • 我仍然遇到同样的错误
  • 你能分享一下你出错的那一行吗?
猜你喜欢
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-01
  • 2021-08-05
  • 2020-10-24
  • 2022-12-17
  • 2020-08-25
相关资源
最近更新 更多