✨ Setup data
This commit is contained in:
46
lib/controllers/food_data.dart
Normal file
46
lib/controllers/food_data.dart
Normal file
@ -0,0 +1,46 @@
|
||||
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);
|
||||
}
|
||||
|
||||
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': 'Foundation',
|
||||
'pageSize': 25,
|
||||
'pageNumber': 1,
|
||||
'sortBy': 'dataType.keyword',
|
||||
'sortOrder': 'asc',
|
||||
'api_key': getApiKey(),
|
||||
},
|
||||
);
|
||||
|
||||
final result = FoodDataQueryResponse.fromJson(resp.data);
|
||||
return result;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user