flutter - Flutter 在其他文件中使用 Future 返回值
问题描述
我有一个问题,我在一个文件(Recipe.dart)中有一个名为 fetchAll() 的方法,我需要它来返回我的食谱列表,为此我创建了一个 Future:
Future<List<Recipe>> recipes() async {
// Get a reference to the database.
final Database db = await database;
// Query the table for all The Recipes.
final List<Map<String, dynamic>> title = await db.query('Rezepte');
final List<Map<String, dynamic>> ingredients = await db.query('Zutaten');
final List<Map<String, dynamic>> preperation =
await db.query('Zubereitungen');
final List<Map<String, dynamic>> imgUrl = await db.query('Images');
// Convert the List<Map<String, dynamic> into a List<Recipe>.
return List.generate(title.length, (i) {
return Recipe(
id: i,
name: title[i]['Rezept_Title'],
ingredients: ingredients[i]['Zutat'],
preperation: preperation[i]['Zubereitung'],
imageURL: imgUrl[i]['Image_URl'],
);
});
}
但这是在数据库帮助文件中,否则我无法访问数据库,那么如何连接这些?那么函数 fetchAll() 返回未来收集的食谱列表?
解决方案
这只是您如何实现它的粗略想法。
我将从创建一个RecipiesRepository
.
在那里,您可以有一个方法来获取标题、成分、准备和图像,并将它们全部返回到一个易于阅读的对象中。
您可以使用一种方法在一个请求中获取所有内容,如下所示:
class RecipiesRepository {
Future<RecipeModel> getRecipe(){
return Future.wait([
_getTitle(),
_getIngredients(),
_getPreparation(),
_getImage(),
]).then((results) {
// return an instance of a RecipeModel here from the results
});
}
}
// RecipeModel
class RecipeModel {
final List<Map<String, dynamic>> title;
final List<Map<String, dynamic>> ingredients;
final List<Map<String, dynamic>> preparations;
final List<Map<String, dynamic>> imageUrls;
RecipeModel({
this.title,
this.ingredients,
this.preparations,
this.imageUrls,
});
}
然后你就可以使用FutureBuilder
小部件了。
// Create a new instance of RecipesRepository somewhere, giving you `_recipiesRepository`
FutureBuilder(
future: _recipiesRepository.getRecipe(),
builder: (context, snapshot) {
if (snapshot.hasData) {
// snapshot.data will be your RecipeModel
return List.generate(snapshot.data.title.length, (i) {
return Recipe(
id: i,
name: snapshot.data.title[i]['Rezept_Title'],
ingredients: snapshot.data.ingredients[i]['Zutat'],
preperation: snapshot.data.preparations[i]['Zubereitung'],
imageURL: snapshot.data.imageUrls[i]['Image_URl'],
);
});
else {
// Show a spinner of something for a default view
}
}
)
推荐阅读
- php - Symfony 3.4 和 Doctrine 事件 - 如果抛出异常,是否可以重定向用户?
- java - ROME API 从 RSS 源解析 CDATA 中的图像 URL
- javascript - 将客户端验证代码添加到 .jss 文件中
- sql - 试图计算投诉、原因、更正的数量
- xml - XSD 全部里面的选择
- docker - Redis Windows 错误:连接 ECONNREFUSED 127.0.0.1:6379 但应用程序正在运行
- java - 我们是否允许分发早期访问 JDK 构建生成的代码?
- python - Python - put_item() S3、Lambda、DynamoDB -- 发生错误 (ValidationException)
- rust - 当 Rust FFI 函数将没有 #[repr(C)] 的结构返回给 C 时,会返回什么?
- vue.js - vue.js bootstrap-datepicker 没有改变值