i have a little problem with Timer.periodic an cancel, i have function which takes information from an api each seconds it works well the problem is that i can't stop it when i want by using Timer.cancel. this is my error:Instance member 'cancel' can't be accessed using static access
void checking() {
Timer.periodic(const Duration(seconds: 1), (check) {
Future<void> recup() async {
try {
var url = Uri.parse('https://konamicash.com/verification_cron');
var response = await http.get(url);
print(response.statusCode);
print('get no');
if (response.statusCode == 200) {
var reponse = jsonDecode(response.body);
var message = reponse['situation'];
print(message);
print(reponse);
if (message == 1) {Timer.cancel();
},
),
);
}
}
} catch (e) {
print('erreur $e');
}
}
recup();
});
}
your Timer
callback is check
so fix it by check.cancel()
but it will only work in periodic function try this solution
1). Define Timer
variable
Timer? timer
2). Assign timer
with timer.periodic()
timer = Timer.periodic(
Duration(milliseconds : 500), (_) async {
// Activity here
}
)
now you will able to access timer (timer?.cancel()
) from the other function and easy to read