hi developers, I hope you are very well, Today I explain “how to countdown Timer in OTP Verification in a flutter”.
To create a countdown timer in OTP verification in a Flutter app, you can use the CountdownTimer class provided by the flutter_countdown_timer package. Here’s an example of how you can use this class to create a countdown timer in an OTP verification.
Let’s Start
- First, add the flutter_countdown_timer package to your dependencies in the pubspec.yaml file.
- In the OTP verification screen, create a variable to hold the total duration of the timer, for example, int _startTime = 15;
- Initialize a Count down Timer (_countTimer) object with the total duration, and a callback function that will be called every time the timer updates.
Intilaization Timer Object
late Timer _timer;
int _startTime = 15;
4. Start the timer using the start() method of the _countTimer object.
_startTime.start();
5. Use the Text widget to display the remaining seconds to the user.
CountdownTimer _countTimer = CountdownTimer(
duration: Duration(seconds: _startTime),
onTimerUpdate: (int remainingSeconds) {
setState(() {
_remainingSeconds = remainingSeconds;
});
}
);
6. You can stop the timer by calling the stop() method of the _countTimer object.
@override
void dispose() {
super.dispose();
_countTimer.stop();
_timer.cancel();
}
Timer Function
void startTimer() {
const oneSec = Duration(seconds: 1);
_timer = new Timer.periodic(
oneSec,
(Timer timer) => setState(
() {
if (_start < 1) {
timer.cancel();
} else {
_start = _start - 1;
}
},
),
);
}
OTP Resend Method
Future<void> resendM() async {
_start = 15; //_start - 1;
setState(() {
startTimer();
});
textWidget();
// Enter hare your API Code to resend the OTP on your Mobile number.
});
}
If you need the create an API in the Flutter app please go through our API integration article.
Timer Start at a widget in a flutter
Widget textWidgetInfo() {
if (_start > 0) {
print(_start);
return AutoSizeText(
"Wait $_start",
style: GoogleFonts.montserrat(
fontSize: 12,
color: WidgetColors.TextColor,
),
);
} else {
return InkWell(
child: AutoSizeText(
"Resend", //
style: GoogleFonts.montserrat(
fontSize: 12,
color: WidgetColors.MainTitleColor,
),
),
onTap: () {
startTimer();
resendM();
},
);
}
}
TextButton Add on OTP Screen in Futter
TextButton(
onPressed: () => snackBar("OTP resend!!"),
child: Padding(
padding: const EdgeInsets.only(right: 29.0),
child: textWidgetInfo(),
)
)
I hope it was a useful article, please share and subscribe to my channel, Thanks for reading and if you have any questions or comments, See you soon.