草庐IT

flutter - 无法将 rest api json 转换为 dart 对象

coder 2023-07-22 原文

在使用 jsondecode 转换 rest api 响应后无法循环

我有来自 laravel 后端的 rest api,我正在尝试使用 flutter 应用程序。 使用 jsondecode 转换响应后无法遍历它并制作一个列表以在小部件 View 中使用

api JSON 响应:

{
    "success": true,
    "data": [
        {
            "id": 1,
            "user_id": 1,
            "mobile_num": "34567",
            "date_before": "2018-12-20 00:00:00",
            "cargo_id": 3,
            "weight": 12,
            "description": "medical stoer",
            "country_id": 22,
            "deleted_at": null,
            "created_at": "2018-12-25 10:42:35",
            "updated_at": "2018-12-25 10:42:35"
        },
        {
            "id": 2,
            "user_id": 3,
            "mobile_num": "21345",
            "date_before": "2018-12-12 00:00:00",
            "cargo_id": 3,
            "weight": 3,
            "description": "welcome by the",
            "country_id": 3,
            "deleted_at": null,
            "created_at": "2018-12-25 10:43:02",
            "updated_at": "2018-12-25 10:43:02"
        },
        {
            "id": 3,
            "user_id": 2,
            "mobile_num": "2342344543",
            "date_before": "2018-12-12 00:00:00",
            "cargo_id": 5,
            "weight": 44,
            "description": "hello maseer",
            "country_id": 3,
            "deleted_at": null,
            "created_at": "2018-12-25 10:44:16",
            "updated_at": "2018-12-25 10:44:16"
        }
    ],
    "message": "Senders retrieved successfully"
}

http 获取响应码:

  Future<dynamic> _getData(String url) async {
    var response = await http.get(url);
    var data = json.decode(response.body);
    return data;
  }

 Future<List<Sender>> getSenders() async {
    var data = await _getData(_baseUrl);
    List<dynamic> sendersData = data['data'];
    print(sendersData);
    print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    //code stop in this point not loop through sendersData***********
    List<Sender> senders =
        sendersData.map((s) => Sender.fromMap(s)).toList();
    print("yyyyyyyyyyyyyyyyyyyyyyyyyyy");
    print(senders);
    // print(senders.length);
    return senders;
  }

模型代码:

class Sender {
  String id,
      userId,
      mobileNum,
      dateBefore,
      cargoId,
      weightS,
      descriptionS,
      countryId,
      createdAt;
  Sender({
    this.id,
    this.userId,
    this.mobileNum,
    this.dateBefore,
    this.cargoId,
    this.weightS,
    this.descriptionS,
    this.countryId,
    this.createdAt,
  });

  Sender.fromMap(Map<String, dynamic> map) {
    id = map['id'];
    userId = map['user_id'];
    mobileNum = map['mobile_num'];
    dateBefore = map['date_before'];
    cargoId = map['cargo_id'];
    weightS = map['weight'];
    descriptionS = map['description'];
    countryId = map['country_id'];
    createdAt = map['created_at'];
  }
}

此代码不执行:列出发件人 = sendersData.map((s) => Sender.fromJson(s)).toList();

没有返回 View

最佳答案

id,userId等是整数值,不是字符串。

    class Sender {
  int id;
  int userId;
  String mobileNum;
  String dateBefore;
  int cargoId;
  int weight;
  String description;
  int countryId;
  String deletedAt;
  String createdAt;
  String updatedAt;

  Sender(
      {this.id,
      this.userId,
      this.mobileNum,
      this.dateBefore,
      this.cargoId,
      this.weight,
      this.description,
      this.countryId,
      this.deletedAt,
      this.createdAt,
      this.updatedAt});

  Sender.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    userId = json['user_id'];
    mobileNum = json['mobile_num'];
    dateBefore = json['date_before'];
    cargoId = json['cargo_id'];
    weight = json['weight'];
    description = json['description'];
    countryId = json['country_id'];
    deletedAt = json['deleted_at'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['user_id'] = this.userId;
    data['mobile_num'] = this.mobileNum;
    data['date_before'] = this.dateBefore;
    data['cargo_id'] = this.cargoId;
    data['weight'] = this.weight;
    data['description'] = this.description;
    data['country_id'] = this.countryId;
    data['deleted_at'] = this.deletedAt;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    return data;
  }
}

结果

flutter: [{id: 1, user_id: 1, mobile_num: 34567, date_before: 2018-12-20 00:00:00, cargo_id: 3, weight: 12, description: medical stoer, country_id: 22, deleted_at: null, created_at: 2018-12-25 10:42:35, updated_at: 2018-12-25 10:42:35}, {id: 2, user_id: 3, mobile_num: 21345, date_before: 2018-12-12 00:00:00, cargo_id: 3, weight: 3, description: welcome by the, country_id: 3, deleted_at: null, created_at: 2018-12-25 10:43:02, updated_at: 2018-12-25 10:43:02}, {id: 3, user_id: 2, mobile_num: 2342344543, date_before: 2018-12-12 00:00:00, cargo_id: 5, weight: 44, description: hello maseer, country_id: 3, deleted_at: null, created_at: 2018-12-25 10:44:16, updated_at: 2018-12-25 10:44:16}]
flutter: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
flutter: yyyyyyyyyyyyyyyyyyyyyyyyyyy
flutter: [Instance of 'Sender', Instance of 'Sender', Instance of 'Sender']

关于flutter - 无法将 rest api json 转换为 dart 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53976670/

有关flutter - 无法将 rest api json 转换为 dart 对象的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  5. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  6. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  7. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  8. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  9. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  10. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

随机推荐