DietaryGuard/lib/controllers/food_data.dart

55 lines
1.4 KiB
Dart
Raw Permalink Normal View History

2024-08-14 17:26:42 +00:00
import 'package:dietary_guard/models/food_data.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
class FoodDataController extends GetxController {
RxBool isReady = false.obs;
late final SharedPreferences _prefs;
Future<void> initialize(BuildContext context) async {
if (isReady.value) return;
_prefs = await SharedPreferences.getInstance();
isReady.value = true;
}
String? getApiKey() {
return _prefs.getString("data_fdc_api_key");
}
Future<void> setApiKey(String value) async {
await _prefs.setString("data_fdc_api_key", value);
}
List<String>? getDataCollections() {
return _prefs.getStringList("data_enabled_collections");
}
Future<void> setDataCollections(List<String> value) async {
await _prefs.setStringList("data_enabled_collections", value);
}
2024-08-14 17:26:42 +00:00
Future<FoodDataQueryResponse> searchFood(String probe) async {
final client = Dio();
final resp = await client.get(
'https://api.nal.usda.gov/fdc/v1/foods/search',
queryParameters: {
'query': probe,
'dataType': getDataCollections()?.join(','),
'pageSize': 100,
2024-08-14 17:26:42 +00:00
'pageNumber': 1,
'sortBy': 'dataType.keyword',
'sortOrder': 'asc',
'api_key': getApiKey(),
},
);
final result = FoodDataQueryResponse.fromJson(resp.data);
return result;
}
}