初学者:如何结合一个SearchView与Openfoodfacts_dart



我是一个完全的编程初学者。但我需要一个应用程序(长话短说:我的儿子有糖尿病,需要一个应用程序来计算碳水化合物…)

我想创建一个搜索视图(文本字段输入搜索项和列表视图(信息从Openfoodfacts特别是产品和品牌,稍后在详细视图与更多的营养信息)。这应该与Openfoodfacts联系起来。有一个依赖,几乎所有准备API调用(Openfoodfacts_dart)。但我没有取得进展。有人能帮帮我吗?

我该如何开始?我在哪里可以找到例子来学习我实际上无法实现的。

我一直在玩OpenFoodFacts API,为了开发这个应用程序,你正在寻找的主要问题是API总是要求你输入条形码,没有办法输入单词,它只返回一个结果。这是API的内在问题,也许其他API可以更好地满足您的需求。

无论如何,想要编写一个几乎没有编程经验的应用程序会让你发疯。我建议你一步一步地学习,从任何语言(Python、java、javascript等)的入门教程开始。然后专注于一个颤振的具体过程。youtube上有很多这样的视频。但基本上你需要3个小部件:textField,任意按钮和一个ListView。我还推荐一个状态管理器,比如provider。为了保持简单,提供程序将具有搜索文本字段中引入的数据的函数,并且它将从按钮触发。

我也建议你寻找替代方案,我不认为你是第一个遇到这个问题的人,也许其他一些应用程序更复杂,但它们也会为你工作。

编码快乐!巴勃罗

编辑:

Future<void> example() async {
final url =
'https://world.openfoodfacts.org/cgi/search.pl?&search_terms=PRODUCT&action=process&json=1&fields=product_name,brands,ingredients_text,carbohydrates_100g,fat_100g,proteins_100g&search_simple=1';
final resp = await http.get(Uri.parse(url)); // api call
Map<String, dynamic> respMap =
json.decode(resp.body); // transform json string into map
List<dynamic> products =
respMap['products']; // get products in a list of maps
List<ProductInfo> productModelList = products
.map((e) => ProductInfo.fromMap(e))
.toList(); // this iterates over the previous list in order to convert each map into an object, then the map of objects is converted to a list.
print(
productModelList); // this will return [Instance of 'ProductInfo', ... ] for each element in the previous list (24 for the url)
}

和我的productInfo类:

import 'dart:convert';
ProductInfo productInfoFromMap(String str) =>
ProductInfo.fromMap(json.decode(str));
String productInfoToMap(ProductInfo data) => json.encode(data.toMap());
class ProductInfo {
ProductInfo({
required this.brands,
required this.carbohydrates100G,
required this.fat100G,
required this.ingredientsText,
required this.productName,
required this.proteins100G,
});
String? brands;
num? carbohydrates100G;
num? fat100G;
String? ingredientsText;
String? productName;
num? proteins100G;
factory ProductInfo.fromMap(Map<String, dynamic> json) => ProductInfo(
brands: json["brands"],
carbohydrates100G: json["carbohydrates_100g"],
fat100G: json["fat_100g"],
ingredientsText: json["ingredients_text"],
productName: json["product_name"],
proteins100G: json["proteins_100g"],
);
Map<String, dynamic> toMap() => {
"brands": brands,
"carbohydrates_100g": carbohydrates100G,
"fat_100g": fat100G,
"ingredients_text": ingredientsText,
"product_name": productName,
"proteins_100g": proteins100G,
};
}

你的类必须有从a到json的转换方法。我用quicktype打印,非常方便。您可能会遇到一些问题,例如必须将整型转换为双精度并进行反向转换,因为有些数据可以发送为整型或双精度。你可以在toMap和fromMap上控制这个,但为了简单起见,如果一个变量可以是int或double,只使用num。此外,你的问题似乎是,有些值可能是空的,像以前一样,你可以控制那些在你的toMap和fromMap函数,或者,我做了什么,使用'?` ` on对象类型声明,允许我们从带有空值的Map转换。

如果你是一个初学者编码,你已经做出了一个很好的选择与扑动。欢迎来到SackOverflow;)

我建议你在Udemy等平台上购买一门关于Flutter的课程。当我开始的时候,它帮了我很多。

最新更新