Reputation: 427
I have a function which is used in several files, in it I use setState(() {});
and some variables that are in the file, can I somehow separate it into another file and call it from there, and not write it on each page?
Here is an example of my function:
Future addToFav(productId, int index) async {
var url =
'${Constants.API_URL_DOMAIN}action=favorite_toggle&token=${Constants.USER_TOKEN}&product_id=$productId';
http.Response response = await http.get(
Uri.parse(url),
);
dynamic body = jsonDecode(response.body);
print(body['success']);
print(body['message']);
if(body['message'] == 'ADDED') {
setState(() => _isFavLoading.add(index));
} else {
setState(() {
_isFavLoading.remove(index);
isFavorite = false;
});
}
}
Upvotes: 0
Views: 136
Reputation: 1473
Because you cannot update the state with setState()
outside of the widget. You have to pass the logic that updates the state as parameter to the function, so you will get such function:
Future<void> addToFav({
required int productId,
required int index,
VoidCallback? onAdded,
VoidCallback? onRemoved,
}) async {
var url =
'${Constants.API_URL_DOMAIN}action=favorite_toggle&token=${Constants.USER_TOKEN}&product_id=$productId';
http.Response response = await http.get(
Uri.parse(url),
);
dynamic body = jsonDecode(response.body);
print(body['success']);
print(body['message']);
if (body['message'] == 'ADDED') {
onAdded?.call();
} else {
onRemoved?.call();
}
}
In the widget you will call this function like this:
ElevatedButton(
onPressed: () {
addToFav(
index: index,
productId: productId,
onAdded: () {
setState(() => _isFavLoading.add(index));
},
onRemoved: () {
setState(() {
_isFavLoading.remove(index);
isFavorite = false;
});
},
);
},
child: Text('Fav'),
)
Upvotes: 1