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 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 setApiKey(String value) async { await _prefs.setString("data_fdc_api_key", value); } List? getDataCollections() { return _prefs.getStringList("data_enabled_collections"); } Future setDataCollections(List value) async { await _prefs.setStringList("data_enabled_collections", value); } Future 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': 25, 'pageNumber': 1, 'sortBy': 'dataType.keyword', 'sortOrder': 'asc', 'api_key': getApiKey(), }, ); final result = FoodDataQueryResponse.fromJson(resp.data); return result; } }