import 'package:flutter/material.dart'; import '../config/AppSnackbar.dart'; import '../models/userAddress_model.dart'; import '../services/myAddress_services.dart'; class UserAddressProvider extends ChangeNotifier { final UserAddressService _service = UserAddressService(); List _addresses = []; List _addressesHome = []; List _addressesWork = []; List _historie = []; bool _isLoading = false; List get addresses => _addresses; List get addressesHome => _addressesHome; List get addressesWork => _addressesWork; List get historie => _historie; bool get isLoading => _isLoading; Future fetchAddresses() async { _isLoading = true; notifyListeners(); try { final response = await _service.getAllAddresses(); print( 'User address response.isValidResponse : ${response.isValidResponse}'); print('response.data : ${response.data}'); if (response.isValidResponse) { _addresses = response.data!; } else { print("Error: ${response.errorMessage}"); } } catch (e) { debugPrint('Error fetching addresses: $e'); } finally { _isLoading = false; notifyListeners(); } } Future fetchAddressesHomeWork() async { _isLoading = true; notifyListeners(); try { final response = await _service.getHistorieWorkHome(); print( 'User address response.isValidResponse : ${response.isValidResponse}'); print('response.data : ${response.data}'); if (response.isValidResponse) { _addressesHome = response.data!.homeAddresses; _addressesWork = response.data!.officeAddresses; _addresses = response.data!.histories; notifyListeners(); } else { print("Error: ${response.errorMessage}"); } } catch (e) { debugPrint('Error fetching addresses: $e'); } finally { _isLoading = false; notifyListeners(); } } Future fetchHistorie() async { _isLoading = true; notifyListeners(); try { final response = await _service.getHistorie(); print('History response.isValidResponse : ${response.isValidResponse}'); print('response.data : ${response.data}'); if (response.isValidResponse) { _historie = response.data!; } else { print("Error: ${response.errorMessage}"); } } catch (e) { debugPrint('Error fetching addresses: $e'); } finally { _isLoading = false; notifyListeners(); } } Future addAddress(List address) async { await _service.addAddress(address); await fetchAddressesHomeWork(); // Refresh list } Future deleteAddress( int id, ) async { _addresses.removeWhere((element) => element.id != null && element.id == id); notifyListeners(); final response = await _service.deleteAddress(id); if (response.isValidResponse) { AppSnackbar.showSuccess( "Success", "Address deleted successfully", ); fetchAddressesHomeWork(); } else { AppSnackbar.showError( "Error", "Error when trying to delete address please try again later", ); } } }