应为“ProductList”类型的值,但得到“_Future<ProductList>”类型的值

时间:2021-05-06 14:18:15

标签: flutter flutter-futurebuilder

我正在尝试使用 rest api 数据返回地图列表,每个地图都包含产品详细信息,因此我使用实现了 fromJsom 方法的 product 和 productList 编码类,然后我尝试在我的 flutter 应用程序中显示 thoes 产品使用 list.generate 但得到错误“期望类型为 'ProductList' 的值,但得到类型为 '_Future' 的值”

这里是负责调用api的函数,它返回一个ProductList类型的Future:

Future<ProductList> loadProductsByIdService(_serviceid) async {

  var datamap = {'service_id': _serviceid};
  var data = json.encode(datamap);
  ProductList products;

  final response = await http.post(Uri.parse(PRODUCTS),
      headers: {
        "Accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: data,
      encoding: Encoding.getByName("utf-8"));

  if (response.body.isNotEmpty) {

    if (response.statusCode == 200) {
      products = ProductList.fromJson(json.decode(response.body));
     
    }

  } else {
    throw Exception('echec de chargement des produits');
  }

  return products;
}

这里是负责展示产品的类

class PopularProducts extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var products = loadProductsByIdService(1) as ProductList;

    return Column(
      children: [
        Padding(
          padding:
              EdgeInsets.symmetric(horizontal: getPropotionalScreenWidth(20)),
          child: SectionTitle(title: "Produits à la Une", press: () {}),
        ),
        SizedBox(height: getPropotionalScreenWidth(20)),
        SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Row(
            children: [
              ...List.generate(
                products.products.length,
                (index) {
                  return ProductCard(product: products.products[index]);
                },
              ),
              SizedBox(width: getPropotionalScreenWidth(20)),
            ],
          ),
        )
      ],
    );
  }
}

我也收到此错误: “errors.dart:187 Uncaught (in promise) Error: FormatException: SyntaxError: Unexpected end of JSON input”

2 个答案:

答案 0 :(得分:1)

您试图在获得数据之前绘制数据。您必须将列包装在 futureBuilder 中以等待该数据。

return FutureBuilder<ProductList>(
      future: loadProductsByIdService(1),
      builder: (context, snapShot) {
        if (snapshot.hasData) {
          return Column(
            children: [
              Padding(
                padding:
                    EdgeInsets.symmetric(horizontal: getPropotionalScreenWidth(20)),
                child: SectionTitle(title: "Produits à la Une", press: () {}),
              ),
              SizedBox(height: getPropotionalScreenWidth(20)),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: [
                    ...List.generate(
                      snapShot.products.length,
                      (index) {
                        return ProductCard(product: snapShot.products[index]);
                      },
                    ),
                    SizedBox(width: getPropotionalScreenWidth(20)),
                  ],
                ),
              )
            ],
          ); 
        } else {
          return SizedBox();
        }
      },
    );

答案 1 :(得分:0)

因为,您必须等待该数据。或者,使用 FutureBuilder 获取该数据,这对我来说是最佳选择。