Flutter Api 响应列表动态不是未来的子类型

Flutter Api Response List dynamic is not subtype of future

你好,我有一个颤振响应,只有一个响应,它给了我一个来自 api

的产品名称
[
{
"pname":"xyz"
}
]

我想在文本字段上解析和显示 pname 值我尝试了以下方法

    Future<ProductsRequest> pnames() async {
      var url= 'https:abc.com/api/p';
      final response = await http.get(Uri.parse(url)).timeout(Duration(seconds: 105000));
      var responseJson = json.decode(response.body);
     
      return responseJson;
    
    }

型号

List<ProductsRequest> productsrequestFromJson(String str) => List<ProductsRequest>.from(json.decode(str).map((x) => ProductsRequest.fromJson(x)));

String productsrequestToJson(List<ProductsRequest> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class ProductsRequest {
  ProductsRequest({
    this.pname,
  });

  String pname;

  factory ProductsRequest.fromJson(Map<String, dynamic> json) => ProductsRequest(
    pname: json["pname"],
  );

  Map<String, dynamic> toJson() => {
    "pname": pname,
  };
}

然后在我的飞镖上class

  new FutureBuilder<ProductsRequest>(
            future: pnames(""),
            builder: (BuildContext context, snapshot) {....
Widget _pdisplay(ProductsRequest data) {
    return Container(
      child:Column(
        children: [
          Text(data.pname.toString()),

        ],

      )

    );

显示错误 List dynamic is not subtype of future

首先,您在响应中得到的是一个列表。而您尝试 return 只是原始响应的解码版本。

所以您需要做的就是对解码后的响应执行 forEach 并列出 ProductsRequest。

像这样:

  List<ProductsRequest> list = new List<ProductsRequest>();
  responseJson.forEach((v) {
    list.add(new ProductsRequest.fromJson(v));
  });