我有几个从 flutter 到 API 的 GET 请求,我希望尽可能高效地运行它。我仍在学习 Flutter,并且来自 JS 背景,我在 Javascript 中使用了类似于 Promise.all([ ... ])
的模式,但我觉得这是一个 hack 而不是解决方案。
如果有更好的方法,我期待阅读:
final apiProvider = new ApiProvider();
final apiData = await Future.wait([
apiProvider.getProducts(), // Returns Future<List<Product>>
apiProvider.getCategories(), // Returns Future<List<Category>>
apiProvider.getBrands(), // Returns Future<List<Brand>>
apiProvider.getCustomers(), // Returns Future<List<Customer>>
]);
List<Product> products = apiData[0];
List<Category> categories = apiData[1];
List<Brand> brands = apiData[2];
List<Customer> customers = apiData[3];
答案 0 :(得分:2)
使用 Future.wait
是合适的。我个人会 await
一个直接设置变量的 Future<void>
列表,这将避免以后使用索引的需要(从而避免潜在的错误)并提高类型安全性:
final apiProvider = ApiProvider();
List<Product> products;
List<Category> categories;
List<Brand> brands;
List<Customer> customers;
await Future.wait([
Future<void>(() async => products = await apiProvider.getProducts()),
Future<void>(() async => categories = await apiProvider.getCategories()),
Future<void>(() async => brands = await apiProvider.getBrands()),
Future<void>(() async => customers = await apiProvider.getCustomers()),
]);