This article is launched on the wechat public account “AndroidTraveler”.
Today I will talk about the implementation of the timer/countdown inside Flutter.
There are generally two scenarios:
- I just need you to call me back when the specified time is up. The callback only needs to happen once.
- I need you to call me back after the specified time. The callback can be multiple times.
Here is how to use Flutter in both scenarios.
The timer that calls back once
const timeout = const Duration(seconds: 5);
print('currentTime='+DateTime.now().toString()); Timer(timeout, () {// Then callbackprint('afterTimer='+DateTime.now().toString());
});
Copy the code
Here we set the timeout to 5 seconds. Then a timer is started, and when the 5 seconds mark is reached, the callback method is executed.
We added the print log before and after the timer started, and the console printed the following output:
CurrentTime =2019-06-08 13:56:35.347493 FLUTTER: afterTimer=2019-06-08 13:56:40.350412Copy the code
Usage can be summarized as:
Set timeout. 2. Start the Timer(timeout, callback) 3. Handle callback
Callback timer multiple times
The use of multiple callback timers is similar to that of a single callback, with the following two differences:
- Different API calls
- You need to cancel manually, otherwise the callback will keep going, because it’s periodic
Similarly, let’s use a simple little example to illustrate:
int count = 0;
const period = const Duration(seconds: 1);
print('currentTime='+DateTime.now().toString()); Timer. Periodic (period, (Timer) {// Then callbackprint('afterTimer='+DateTime.now().toString());
count++;
if(count >= 5) {// Cancel the timer to avoid infinite callback timer.cancel(); timer = null; }});Copy the code
In this case, our function is to call back once per second, and when it reaches 5 seconds, the timer is cancelled, so it calls back 5 times in total.
The console output is as follows:
CurrentTime =2019-06-08 14:16:03.909963 flutter: currentTime=2019-06-08 14:16:03.909963 AfterTimer =2019-06-08 14:16:03.910538 flutter: afterTimer=2019-06-08 14:16:03.911942 flutter: AfterTimer =2019-06-08 14:16:06.911741 flutter: afterTimer=2019-06-08 14:16:07.910227Copy the code
Usage can be summarized as:
Set the periodic callback period. 2. Enable Timer. Periodic (period, callback(Timer)) 3. Callback (timer) 4. Remember to cancel the timer when appropriate, otherwise the callback will continue
Ok, with the above knowledge reserve, next, let’s enter the actual combat.
Practical interpretation of the
The business scenario
The server returns a time, you according to the server time and the current time comparison, display countdown, countdown time within a day, more than a day to display the default copy.
Scenario analysis
This business scenario needs to use our knowledge above in the countdown. Since the countdown is limited to one day, the text is displayed from 00:00:00 to 23:59:59.
Specific code operation
Basic idea: first we need to get the remaining time, then start a 1-second periodic timer, and then update the copy every second.
Directly on the code:
String constructTime(int seconds) {int hour = seconds ~/ 3600; String constructTime(int seconds) {int hour = seconds ~/ 3600; int minute = seconds % 3600 ~/ 60; int second = seconds % 60;return formatTime(hour) + ":" + formatTime(minute) + ":"+ formatTime(second); } String formatTime(int timeNum) {String formatTime(int timeNum) {return timeNum < 10 ? "0"+ timeNum.toString() : timeNum.toString(); } var now = datetime.now (); Var twoHours = now.add(Duration(minutes: 2)). Difference (now); Var seconds = twohours.inseconds; Const period = const Duration(seconds: 1); // Print the initial time format of 00:02:00print(constructTime(seconds)); Timer. Periodic (period, (Timer) {// Periodic (period, (Timer) { // Print the time after minus oneprint(constructTime(seconds));
if(seconds == 0) {// If the timer is 0, cancel timer.cancel(); timer = null; }});Copy the code
In fact, notes are also written very clear, is the basic idea of the basis of the increase in some details, here is a demonstration of their own structure of a two-minute countdown.
Ok, that’s basically it, but there may be some different details about Flutter. Here is the complete code for the next countdown.
import 'dart:async';
import 'package:flutter/material.dart';
class Countdown extends StatefulWidget {
@override
_CountdownState createState() => _CountdownState();
}
class _CountdownState extends State<Countdown> {
Timer _timer;
int seconds;
@override
Widget build(BuildContext context) {
returnCenter( child: Text(constructTime(seconds)), ); String constructTime(int seconds) {int hour = seconds ~/ 3600; String constructTime(int seconds) {int hour = seconds ~/ 3600; int minute = seconds % 3600 ~/ 60; int second = seconds % 60;return formatTime(hour) + ":" + formatTime(minute) + ":"+ formatTime(second); } String formatTime(int timeNum) {String formatTime(int timeNum) {return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
}
@override
void initState() { super.initState(); Var now = datetime.now (); Var twoHours = now.add(Duration(minutes: 2)). Difference (now); // Get the total number of seconds. Seconds = twohours.inseconds; startTimer(); } voidstartTimerConst period = const Duration(seconds: 1); _timer = timer.periodic (period, (Timer) {// Updates the interfacesetState(() {// The number of seconds is reduced by one, because seconds are called once a second --; });if(seconds == 0) {// If the timer is 0, cancel the timer (); }}); } voidcancelTimer() {
if(_timer ! = null) { _timer.cancel(); _timer = null; } } @override voiddispose() { super.dispose(); cancelTimer(); }}Copy the code
The effect is as follows:
In the future, I plan to write an example of FlutterApp covering my previous blog, so that you can check the actual operation effect with the code. Please look forward to it.
We have created a knowledge planet here. We welcome Internet friends to join us, learn and grow together. I am discussing some interesting topics with my friends Flutter. Why don’t you join me? t.zsxq.com/MVrJiAY
Scanning to add: