HTTP GET 请求结果放入数组

时间:2021-07-24 18:57:38

标签: flutter dart

所以我有这个 http req 负载,我想把它推到一个数组中,有人可以帮我吗?

有效载荷

{
   "status":200,
   "length":3,
   "results":[
      {
         "_id":"60cd70b3fb9fe400117e8c6b",
         "title":"Welcome to xxx",
         "body":"Welcome to xx! We’re excited that everyone’s here and hope your ready for an epic weekend."
      },
      {
         "_id":"60cd70b3fb9fe400117e8c6c",
         "title":"Lunch Info",
         "body":"Lunch is from our generous sponsors Lorem Ipsum! It will be served in the left atrium under the palm trees."
      },
      {
         "_id":"60cd70b3fb9fe400117e8c6d",
         "title":"Leash Dogs",
         "body":"A friendly reminder that dogs must be leashed at all times, no matter how cute <3"
      }
   ]
}

我的提供商代码 [更新]

//所以我尝试自己调试,1号和2号被打印出来,3号没有。我怀疑是因为我处理提取数据的方式。

 class Announcements {
  int? status;
  int? length;
  List<Results>? results;

  Announcements(
      {required this.status, required this.length, required this.results});

  Announcements.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    length = json['length'];
    if (json['results'] != null) {
      results = [];
      json['results'].forEach((v) {
        results!.add(new Results.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['status'] = this.status;
    data['length'] = this.length;
    if (this.results != null) {
      data['results'] = this.results!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}
// so i've used your online converter json
class Results {
  String? sId;
  String? title;
  String? body;

  Results({required this.sId, required this.title, required this.body});

  Results.fromJson(Map<String, dynamic> json) {
    sId = json['_id'];
    title = json['title'];
    body = json['body'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['_id'] = this.sId;
    data['title'] = this.title;
    data['body'] = this.body;
    return data;
  }
}

class AnnouncementProvider with ChangeNotifier {
  AnnouncementProvider(String? token, items);
  List _items = [];
  List get items {
    return [..._items];
  }

  // List<Announcements> parseAnnouncement(String responseBody) {

  // }

  Future<List<Announcements>> fetchAnnouncements(String authToken) async {
    //var url = Uri.https('api-staging.xxx.us.org', '/1.0/announcements');
    final response = await http.get(
      Uri.parse('https://api-staging.xxx.us.org/1.0/announcements'),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $authToken',
      },
    );
    print(response.body);
    final t = Announcements.fromJson(response.body as Map<String, dynamic>);
    print(t.results);
    return t.results;
  }
}

我需要知道的是,我如何正确返回列表,因为由于某种原因实际上没有打印 print(t.results),所以现在它只在我的界面中显示“发生错误”。 感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

考虑为此创建一个 Dart 模型对象,我强烈建议您这样做,因为这可以保证序列化和类型安全

对于您的情况,我为您从 api 端点接收的数据类型使用了一个假想名称 FoodItems

class FoodItems {
  int status;
  int length;
  List<Results> results;

  FoodItems({this.status, this.length, this.results});

  FoodItems.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    length = json['length'];
    if (json['results'] != null) {
      results = new List<Results>();
      json['results'].forEach((v) {
        results.add(new Results.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['status'] = this.status;
    data['length'] = this.length;
    if (this.results != null) {
      data['results'] = this.results.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Results {
  String sId;
  String title;
  String body;

  Results({this.sId, this.title, this.body});

  Results.fromJson(Map<String, dynamic> json) {
    sId = json['_id'];
    title = json['title'];
    body = json['body'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['_id'] = this.sId;
    data['title'] = this.title;
    data['body'] = this.body;
    return data;
  }
}

现在您可以使用 response.body 方法轻松地将 FoodItems 转换为 fromJson 类,然后获取所需的 Results 列表,然后对其进行迭代 老实说,这种方式让事情变得更简单

注意:我强烈建议您阅读以下内容