【问题标题】:Can anyone help to Fetch the data from this api in flutter任何人都可以帮助从这个 api 中获取数据吗?
【发布时间】:2022-01-13 10:40:52
【问题描述】:

https://www.dubaisuperstore.com.pk//myapi//product

我用颤振制作的模型

class ProductModel {
  String? count;
  List<ProductDetail>? productDetail;

  ProductModel({this.count, this.productDetail});
}

class ProductDetail {
  int? RowId;
  int? SKUId;
  String? SKUName;
  int? SKUCatId;
  String? Category;
  int? SKUSubCatId;
  String? Sub_Category;
  String? SKURemarks;
  String? SKUActive;
  int? SalePrice;
  int? RetailPrice;
  int? SKUDiscPerc;
  String? SKUImageURL1;

  ProductDetail(
      {this.RowId,
      this.SKUId,
      this.SKUName,
      this.SKUCatId,
      this.Category,
      this.SKUSubCatId,
      this.Sub_Category,
      this.SKURemarks,
      this.SKUActive,
      this.SalePrice,
      this.RetailPrice,
      this.SKUDiscPerc,
      this.SKUImageURL1});
}

这是我要获取的 api 的链接,我已检查此 api 的格式为 xml 和 json 尝试帮助我

【问题讨论】:

  • 响应格式是什么?
  • api 的格式是 json 和 xml,我没有通过这个 api 获取任何数据,似乎获取不正确或任何其他问题
  • 检查API的响应,然后尝试在模型类中传递。
  • 对我来说这看起来像 XML,所以使用 xml 包来解析它。 pub.dev/packages/xml 或者询问服务器维护者是否有办法以不同的格式(例如 JSON)请求数据
  • 这个 api 的响应是在 json 中,但是当我们在 chrome 中打开它时,它会显示在 xml 中,我正在尝试但在将其视为 json 时没有获取数据

标签: flutter api


【解决方案1】:

此代码应该可以帮助您入门:

import 'dart:convert';

import 'package:http/http.dart' as http;

void main() async {
  final response = await http.get(
    Uri.parse('https://www.dubaisuperstore.com.pk/myapi/product'),
  );
  final topList = json.decode(response.body) as List;
  final topObject = topList[0] as Map<String, dynamic>;
  print('There are ${topObject['Count']} products! That is a lot!');

  final productList = topObject['productDetail'] as List;
  final secondProduct = productList[1] as Map<String, dynamic>;
  print('The second product is ${secondProduct['SKUName']}. Sounds tasty');

  // at this point you could: productList.map(xxx) to turn all the product JSON objects to your model objects
}

打印出来:

There are 5522 products! That is a lot!
The second product is 3 HORSES MALT DRINK 330ML. Sounds tasty

【讨论】:

  • 如果有帮助,传统的做法是接受答案。 (然后为任何后续问题创建新问题。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 2018-06-03
相关资源
最近更新 更多