颤振/飞镖格式化数据到实例不起作用

Posted

技术标签:

【中文标题】颤振/飞镖格式化数据到实例不起作用【英文标题】:Flutter/dart formatting data to instances not working 【发布时间】:2022-01-21 01:12:06 【问题描述】:

所以,我可以接收数据并打印它,但它不会再正确格式化为列表。我附上了下面用于获取数据和模型的所有代码。加上打印输出。谁能帮帮我。

获取数据

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:world_time/services/model/article_model.dart';
class News 


  String? city;
  List? articles;

  News(this.city);
  Future<void> getNews() async 
    try 

      Response response = await get(Uri.parse('https://newsapi.org/v2/everything?q=$city&from=2021-12-05&sortBy=popularity&apiKey=MY API KEY'));
      Map<String, dynamic> json = jsonDecode(response.body);
      print(json);
      List<dynamic> body = json['articles'];
      articles = body.map((dynamic item) => Article.fromJson(item)).toList();
      print(articles);
    
    catch (e)
      print("Caught error: $e");
    
  

打印(json)

status: ok, totalResults: 520, articles: [source: id: bbc-news, name: BBC News, author: null, title: Unstoppable Salah closes in on more records - his year in numbers, description: As Liverpool's Mohamed Salah closes in on another record, BBC Sport takes a statistical look at his superb 2021., url: https://www.bbc.co.uk/sport/football/59646200, urlToImage: https://ichef.bbci.co.uk/live-experience/cps/624/cpsprodpb/1269A/production/_122081457_mohamedsalah.jpg, publishedAt: 2021-12-16T08:49:23Z, content: Mohamed Salah has scored 36 goals in all competitions for Liverpool in 2021
I/flutter ( 2307): "He is phenomenal. For sure, at the moment, he is the best player in the world."
I/flutter ( 2307): Liverpool manager Jurgen Klopp may well … [+5278 chars], source: id: reuters, name: Reuters, author: null, title: Man Utd face Villa, Leicester host Watford in FA Cup third round - Reuters, description: Manchester United entertain Aston Villa in the FA Cup third round, while holders Leicester City welcome Watford and West Ham United are at home

打印(文章) 由于文章为空,catch 返回此

I/flutter ( 2307): Caught error: type 'Null' is not a subtype of type 'String' in type cast

article_model

class Article 
  Source? source;
  String? author;
  String? title;
  String? description;
  String? url;
  String? urlToImage;
  String? publishedAt;
  String? content;
  Article(
      this.source,
        this.author,
        this.title,
        this.description,
        this.url,
        this.urlToImage,
        this.publishedAt,
        this.content);
  factory Article.fromJson(Map<String, dynamic> json) 
    return Article(
      source: Source.fromJson(json['source']),
      author: json['author'] as String,
      title: json['title'] as String,
      description: json['description'] as String,
      url: json['url'] as String,
      urlToImage: json['urlToImage'] as String,
      publishedAt: json['publishedAt'] as String,
      content: json['content'] as String,
    );
  

source_model

  String? id;
  String? name;

  Source(this.id, this.name);

  factory Source.fromJson(Map<String, dynamic> json) 
    return Source(id: json['id'], name: json['name']);
  

【问题讨论】:

【参考方案1】:

在您的模型上,您的所有变量都是String? 类型,也就是说,变量将是Stringnull。但是当你制作模型时,你会像这样分配所有变量:variable: json['variable'] as String,这意味着如果它们是null,它们会抛出错误,因为你做了as String,而不是as String?,这就是出现错误。

要解决这个问题,我相信应该可以完全删除as String,如下所示:

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

上面的可能不起作用,如果它不起作用,下面的应该:

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

【讨论】:

非常感谢,这对我有用。正如您可能会说的那样,我对颤动很陌生,所以这有助于加载。

以上是关于颤振/飞镖格式化数据到实例不起作用的主要内容,如果未能解决你的问题,请参考以下文章

如何在颤振/飞镖扩展中禁用蓝色警告下划线标志?

飞镖 CORS 不起作用

在飞镖(颤振)中为移动应用创建“签名区域”[关闭]

在颤振飞镖中的 List<Map> 内搜索?

无法在 VS Code 中调试颤振飞镖代码,未验证断点错误

颤振图像上传在真实设备上不起作用,虽然它适用于模拟器