не удается обновить значение списка

#flutter #dart

#сбой #dart

Вопрос:

Я пытаюсь получить товары из своей учетной записи razorpay, но сталкиваюсь с проблемами: значения печатаются, когда я запускаю его из цикла «forEach», но не могу вернуть значения извне цикла. Следующая функция должна вернуть список продуктов, но возвращает null есть идеи о том, что я делаю неправильно?

 Future<List<Product&&t;&&t; fromPlanResponse({http.Response response}) async {
    List<Product&&t; products = [];
    if (response == null)
      return null;
    else {
      var result = json.decode(response.body);
      List items = result['items'];
      items.forEach((product) async {
        final Strin& productId = product['id'];
        final Strin& name = product['item']['name'];
        final int amount = product['item']['amount'];
        final Strin& description = product['item']['description'];
        final Subscription subscription =
            await _subscription.&etSubscriptions(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.toStrin&()); // this prints []
    return products; // this return []
  }```

Output for the above code

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

════════ Exception cau&ht by wid&ets library ═══════════════════════════════════
type 'List<dynamic&&t;' is not a subtype of type 'List<Wid&et&&t;'
The relevant error-causin& wid&et was
    FutureBuilder<List<Product&&t;&&t; 
lib/…/profile/subsciption_screen_razorpay.dart:46
════════════════════════════════════════════════════════════════════════════════
I/flutter (14906): [Instance of 'Product']
I/flutter (14906): [Instance of 'Product', Instance of 'Product']][1]][1]
  

Комментарии:

1. Ошибка, которую вы получаете, не из fromPlanResponse… Это скорее из вашего кода FutureBuilder … любезно добавьте его

2. Ошибка связана с тем, что future builder получает нулевое значение из этой функции, поэтому, если возвращается список продуктов, future builder не выдает эту ошибку, я проверил!

Ответ №1:

Вы не должны возвращаться внутрь forEach цикла. Возврат после. Вот так

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

Таким образом, все продукты были бы добавлены в список перед возвратом