flutter - 无法更新列表值
问题描述
我正在尝试从我的 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]
解决方案
您不应该在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;
}
这样,所有产品在返回之前都会被添加到列表中
推荐阅读
- javascript - 将县的路径添加到我预测的州
- maven - 在詹金斯工作中构建成功后无法部署简单的 JSP Web 应用程序
- python - 熊猫中的文本分组
- node.js - Mongo 的 updateMany 重命名不会更新某些字段
- gcc - 如何将函数或标签的地址加载到寄存器中
- html - 如何将我在 Visual Studio 代码上的本地网站推送到我在 Azure 上部署的 Web 应用程序
- java - 如何使用行尾作为分隔符拆分字符串但将行尾保留在输出中(Java)
- python - 从 Keras model.evaluate 和 model.predict 获得不同的结果
- php - 为什么在运行日期操作时不能用它的表达式替换日期变量?
- javascript - 属性或方法“用户”未定义 vue js 应用程序