我正试图从我的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]
答案 0 :(得分:0)
您不应该在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;
}
这样,所有产品都将在返回之前添加到列表中