calorimeter/lib/food_scan/food_fact_lookup.dart

70 lines
1.7 KiB
Dart
Raw Normal View History

2024-09-06 16:51:24 +00:00
import 'dart:convert';
import 'dart:developer';
2024-09-06 16:51:24 +00:00
import 'dart:io';
class FoodFactLookupClient {
FoodFactLookupClient();
static const String url = "https://world.openfoodfacts.org/api/v3/product/";
String getProductUrl(String ean) {
return "$url$ean.json";
}
Future<FoodFactResponse> retrieveFoodInfo(String ean) async {
2024-09-06 16:51:24 +00:00
HttpClient client = HttpClient();
String asString = "";
try {
var request = await client.getUrl(Uri.parse(getProductUrl(ean)));
var response = await request.close();
if (response.statusCode != HttpStatus.ok) {
return FoodFactResponse(
food: null, status: FoodFactResponseStatus.barcodeNotFound);
}
asString = await response.transform(utf8.decoder).join();
} on SocketException {
return FoodFactResponse(
food: null,
status: FoodFactResponseStatus.foodFactServerNotReachable);
} catch (e) {
log(e.toString());
} finally {
client.close();
}
return FoodFactResponse(
food: FoodFactModel.fromJson(jsonDecode(asString)),
status: FoodFactResponseStatus.ok);
2024-09-06 16:51:24 +00:00
}
}
class FoodFactModel {
final String name;
final int kcalPer100g;
2024-09-06 16:51:24 +00:00
FoodFactModel({required this.name, required this.kcalPer100g});
2024-09-06 16:51:24 +00:00
factory FoodFactModel.fromJson(Map<String, dynamic> json) {
return FoodFactModel(
name: json['product']['product_name'],
kcalPer100g: json['product']['nutriments']['energy-kcal_100g']);
2024-09-06 16:51:24 +00:00
}
}
enum FoodFactResponseStatus {
foodFactServerNotReachable,
barcodeNotFound,
ok,
}
class FoodFactResponse {
final FoodFactModel? food;
final FoodFactResponseStatus status;
FoodFactResponse({required this.food, required this.status});
}