首页 > 解决方案 > 无法更新列表值

问题描述

我正在尝试从我的 razorpay 帐户中获取产品,但是当我从“forEach”循环中运行它但无法从循环外部返回值时,我遇到了问题。以下函数应返回产品列表,但返回 null 关于我做错了什么的任何想法?

Future<List<Product>> fromPlanResponse({http.Response response}) async {
    List<Product> products = [];
    if (response == null)
      return null;
    else {
      var result = json.decode(response.body);
      List items = result['items'];
      items.forEach((product) async {
        final String productId = product['id'];
        final String name = product['item']['name'];
        final int amount = product['item']['amount'];
        final String description = product['item']['description'];
        final Subscription subscription =
            await _subscription.getSubscriptions(productId: productId);
        products.add(Product(
          productId: productId,
          subscription: subscription,
          productName: name,
          description: description,
          amount: amount,
        ));
        print(products); // prints the products here
        // return products; this return does not work
      });
    }
    print("products are " + products.toString()); // this prints []
    return products; // this return []
  }```

Output for the above code

[I/flutter (14906): products are []
I/flutter (14906): []
I/flutter (14906): []

════════ Exception caught by widgets library ═══════════════════════════════════
type 'List<dynamic>' is not a subtype of type 'List<Widget>'
The relevant error-causing widget was
    FutureBuilder<List<Product>> 
lib/…/profile/subsciption_screen_razorpay.dart:46
════════════════════════════════════════════════════════════════════════════════
I/flutter (14906): [Instance of 'Product']
I/flutter (14906): [Instance of 'Product', Instance of 'Product']][1]][1]

标签: flutterdart

解决方案


您不应该在forEach循环内返回。后返回。像这样

Future<List<Product>> fromPlanResponse({http.Response response}) async {
    List<Product> products = [];
    if (response == null)
      return null;
    else {
      var result = json.decode(response.body);
      List items = result['items'];
      items.forEach((product) async {
        final String productId = product['id'];
        final String name = product['item']['name'];
        final int amount = product['item']['amount'];
        final String description = product['item']['description'];
        final Subscription subscription = await_subscription.getSubscriptions(productId: productId);
        products.add(Product(
          productId: productId,
          subscription: subscription,
          productName: name,
          description: description,
          amount: amount,
        ));
        print(products); // prints the products here
      });
    }
    return products;
  }

这样,所有产品在返回之前都会被添加到列表中


推荐阅读