The introduction

In daily development, scenes like countdown are often used, such as delaying the completion of a piece of logic, or loading a flash screen advertisement on the launch page before entering the APP. The more common scenario is the friendly reminder of users’ waiting attempts when obtaining mobile verification codes. In this post we will take a look at the process of encapsulating a countdown widget based on Flutter

Course Knowledge

  • 1. Use of Timer
  • 2. The value passed by the callback function
  • 3. Establishment of the idea of component encapsulation

Before we start today’s blog post, let’s take a look at some renderings of today’s lecture:

rendering

Logical combing

From the diagram above we can analyze that

1. The countdown widget can be divided into two states

  • Countdown: according to the time we set, each time decrease one second, until the remaining time is 0. During this time the button font color is gray and the button cannot receive click events again
  • Initial state or complete countdown: button font color is blue, click the button to enter the countdown state.

2. The countdown logic on the button is completed by using the Timer under the Dart Async package

Timer.periodic(Duration duration, void callback(Timer timer)) 
Copy the code

From the method signature, we can see that timer.periodic receives two parameters, the time interval and the callback function. We use the interval of one second passed in as a period, and then execute it in the callback function, each time the time decreases by one, if the current remaining time is less than one, we terminate the current Timer, otherwise we keep executing the callback function

    Timer _timer;
    int _countdownTime = 10;

    _timer = Timer.periodic(
        Duration(seconds: 1),
            (Timer timer) =>
        {
          setState(() {
            if (_countdownTime < 1) {
              _timer.cancel();
            } else {
              _countdownTime = _countdownTime - 1; }})});Copy the code

The rest of the section deals with the handling of state and click events on buttons, which I covered in a series of articles on getting started. I won’t go into detail here, but you can read the code for yourself.

Packaged countdown Widget code:
import 'dart:async';

import 'package:flutter/material.dart';

/ * * *@desc
 * @author xiedong
 * @date2020-02-28. * /

class TimerCountDownWidget extends StatefulWidget {
  Function onTimerFinish;

  TimerCountDownWidget({this.onTimerFinish}) : super(a);@override
  State<StatefulWidget> createState(a) => TimerCountDownWidgetState();
}

class TimerCountDownWidgetState extends State<TimerCountDownWidget> {
  Timer _timer;
  int _countdownTime = 0;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (_countdownTime == 0) {
          setState(() {
            _countdownTime = 60;
          });
          // Start the countdown
          startCountdownTimer();
        }
      },
      child: RaisedButton(
        color: Colors.black12,
        child: Text(
          _countdownTime > 0 ? '$_countdownTime after retrieve ' : 'Get captcha',
          style: TextStyle(
            fontSize: 14,
            color: _countdownTime > 0
                ? Colors.white
                : Color.fromARGB(255.17.132.255(), ((), ((), ((), ((), (() }void startCountdownTimer(a) {
// const oneSec = const Duration(seconds: 1);
// var callback = (timer) => {
// setState(() {
// if (_countdownTime < 1) {
// widget.onTimerFinish();
// _timer.cancel();
// } else {
// _countdownTime = _countdownTime - 1;
/ /}
/ /})
/ /};
//
// _timer = Timer.periodic(oneSec, callback);


    _timer = Timer.periodic(
        Duration(seconds: 1),
        (Timer timer) => {
              setState(() {
                if (_countdownTime < 1) {
                  widget.onTimerFinish();
                  _timer.cancel();
                } else {
                  _countdownTime = _countdownTime - 1; }})}); }@override
  void dispose(a) {
    super.dispose();
    if(_timer ! =null) { _timer.cancel(); }}}Copy the code
Used as a Widget in a page
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/pages/custom_widget/widget/timer_count_down_widget.dart';

/ * * *@desc
 * @author xiedong
 * @date2020-02-28. * /

class VerficationCodePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState(a) => VerficationCodePageState();
}

class VerficationCodePageState extends State<VerficationCodePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Captcha Countdown"),
        centerTitle: true,
      ),
      body: Center(
        child: TimerCountDownWidget(onTimerFinish: (){
          print("Countdown ends --------"); },),),); }}Copy the code

After running the code, we click the “Get captcha” button, and when the countdown is over, the callback function we passed in will be called, as shown below in the log console printing out what we typed in the program:

This blog related code: blog source code