I'm trying to create a function that adds an item into a table when it doesn't exist yet, but instead of adding the item once and stop executing, it adds the item more than once, even if it's already added. I tried this way:
List<Meal> _items = [];
List<Meal> get items => [..._items];
@override
void initState() {
super.initState();
loadMeals();
}
Future<void> loadMeals() async {
_loggedItems.clear();
// _items.clear();
String? teste = user?.email.toString();
final responseUser = await http.get(
Uri.parse(
'URL/users_login/$teste'), // ${_formData.email}
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
if (responseUser.body == 'null') return;
final data2 = jsonDecode(responseUser.body)['items'] as List?;
// print(teste2);
if (data2 != null) {
_loggedItems = data2.map((e) => UserData.fromMap(e)).toList();
}
final response = await http.get(
Uri.parse(
'URL/pratos/${dropDownService.replaceAll('à', 'a')}/${loggedItems.first.restaurantId}'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json; charset=UTF-8'
},
);
if (response.body == 'null') return;
final data = jsonDecode(utf8.decode(response.bodyBytes))['items'] as List?;
if (data != null) {
_items = data.map((e) => Meal.fromMap(e)).toList();
}
setState(() {});
}
void _menuWithReservation() {
final loggedUserList = Provider.of<LoggedUser>(context, listen: false);
final newItem = MenuMealRestaurant(
menuId: '161',
mealId: (dropDownService == 'gastronomia') ? '6' : '65',
restaurantId: loggedUserList.loggedItems.first.restaurantId,
);
print('chamou');
addMealOnMenu(newItem);
}
Future<void> addMealOnMenu(MenuMealRestaurant menuMealRestaurant) async {
// ignore: unused_local_variable
final future = await http.post(
Uri.parse(
'URL/cardapio_prato_restaurante_post'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
"id_cardapio": menuMealRestaurant.menuId.toString(),
"id_prato": menuMealRestaurant.mealId.toString(),
"id_restaurante": menuMealRestaurant.restaurantId.toString(),
}),
);
_itemsMealAdd.add(menuMealRestaurant);
// return future.then((response) {
// });
}
@override
Widget build(BuildContext context) {
var index = daysMap[dropDownDayOfWeek];
var date = calendar(int.parse(index!));
final reservationButtonExists = _items
.where((element) =>
element.mealName.contains('Reservar') &&
DateFormat('dd-MM-yyyy').format(DateTime.parse(element.date!)) ==
date)
.toList();
if (dropDownService != 'sabor à mesa' &&
_option == Option.reserva &&
reservationButtonExists.isEmpty) {
_menuWithReservation();
}
}
It should only execute the function "_menuWithReservation" while reservationButtonExists is empty, but instead it executes a few couple times before it starts to respect the condition. How can I fix this?