I am currently writing an app using Flutter and Dart. On a button onPressed
event I would like to invoke an action that executes after timeLeft
seconds unless it is cancelled by correctly entering a pin. Additionally, I would like to use the value timeLeft
in a Text widget.
This would require a structure with the following functionality:
- executing a function after an
x
amount of seconds - this function should execute unless some event (e.g. entering a pin correctly) has occurred.
- the
timeLeft
value should be accessible to be used in a Text widget and should update as the timer progresses.
I am wondering how to do this according to flutter's and dart's best practices. For state management I am using the provider pattern so preferably this approach is compatible with the provider pattern.
This is what I have tried so far:
class Home extends ChangeNotifier {
int secondsLeft = 10;
void onPressedEmergencyButton(BuildContext context) {
countDown();
showDialog<void>(
context: context,
builder: (context) {
return ScreenLock(
title: Text(
"Sending message in ${context.read<Home>().secondsLeft} seconds"),
correctString: '1234',
canCancel: false,
didUnlocked: () {
Navigator.pop(context);
},
);
},
);
}
void countDown() {
Future.delayed(const Duration(seconds: 1), () {
secondsLeft =- 1;
notifyListeners();
if (secondsLeft <= 0) {
// Do something
return;
}
});
}
}