I am using Freezed package to create NetworkResponse class to use with Networking manager.
I return Future.value(cartFetched)
in getCartData
method and access it in fetchCart
but value in Future.then
method is always null.
If I change the getCartData
method to return Future<ActionEnum>
then compiler makes me return a Action
value at the end which overwrites/supersedes my return Future.value(ActionEnum.cartFetched)
inside cartData.when
method. How can I return a valid value from getCartData
?
class CartRepository {
Future<void> getCartData(Map<String, Object> requestData) async {
CartEndPoint cart = CartEndPoint();
cart.requestBody = requestData;
try {
NetworkResponse? cartData = await apiManager.fetchData(loginEnd);
cartData.when(success: (response) {
return Future.value(ActionEnum.cartFetched); // Action is a enum
}, loading: (message) {
print("loading - ${message}");
}, error: (error) {
print("error - ${error.message}");
throw error;
});
} catch (error) {
rethrow;
}
}
}
class _CartScreenState extends State<CartScreen> {
fetchCart() {
Future service = CartRepository(). getCartData(requestData);
service.then((value) {
**// value is always null**
if (value is ActionEnum) {
switch (value) {
case ActionEnum.cartFetched:
// do next action
break;
}
}
widget.onChange(true);
}).onError((error, stackTrace) {
print(error);
});
}
}
First, you need to change the return type of getCartData from Future to Future or, in case you want to make it nullable, Future<ActionEnum?>. Then, inside getCartData(), you need to add return before cartData(success: (response)), because the return inside cartData(success: (response)) only returns to that function call, not to getCartData.
Code:
class CartRepository {
Future<ActionEnum> getCartData(Map<String, Object> requestData) async {
CartEndPoint cart = CartEndPoint();
cart.requestBody = requestData;
try {
NetworkResponse? cartData = await apiManager.fetchData(loginEnd);
return cartData(success: (response) {
return Future.value(ActionEnum.cartFetched); // Action is a enum
}, loading: (message) {
print("loading - ${message}");
//Here you need to throw or return something or incase you use nullable then return null
}, error: (error) {
print("error - ${error.message}");
throw error;
});
} catch (error) {
rethrow;
}
}
}
I hope it helps.