Flutter Api Response List dynamic is not subtype of future

Issue

Hello i have a flutter response just single response which gives me a product name from api

[
{
"pname":"xyz"
}
]

I want to parse and and display pname value on text field I have tried the following

    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;
    
    }

model

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,
  };
}

then on my dart class

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

        ],

      )

    );

it shows an error List dynamic is not subtype of future

Solution

First of all, what you are getting in the response is a list. And what you are trying to return is just a decoded version of the raw response.

So what you need to do is just do forEach on that decoded response and make a list of ProductsRequest.

Something like this :

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

Answered By – Meet Prajapati

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *