Flutter verification code countdown Widget package

introduction

In the daily development process, scenarios like countdown are often used, such as delaying the completion of a piece of logic, or loading a splash screen advertisement on the startup page, and then entering the app after the countdown time is up. The more common scenario is that we A waiting attempt to friendly prompt the user when obtaining the mobile phone verification code. In this blog post, we will learn about the whole process of encapsulating a countdown widget based on flutter.

Course knowledge points

  • 1. About the use of Timer
  • 2. Passing the value of the callback function
  • 3. Establishment of the idea of ​​component encapsulation

Before starting today’s blog post, let’s take a look at the renderings of what is being taught in today’s course:

renderings
Insert image description here

Logical sorting

From the above figure we can analyze that

1. The whole process countdown widget is divided into two states.

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

2. We use the Timer under the dart async package to complete the countdown logic on the button.

Timer.periodic(Duration duration, void callback(Timer timer)) 

From the method signature, we can see that Timer.periodic receives two parameters, namely the time interval and the callback function. We use the incoming time interval as a period of 1 second, and then execute it in the callback function. Each time the time is decremented by 1, if the current remaining time is less than 1, we end the current Timer, otherwise the callback function is always executed.

    Timer _timer;
    int _countdownTime = 10;

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

The other parts involve the processing of button status and click events. I have explained them in detail in the series of articles in the entry-level advanced column, so I will not go into details here. Readers can read and understand by themselves based on the code.

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

import 'package:flutter/material.dart';

/**
 * @desc
 * @author xiedong
 * @date   2020-02-28.
 */

class TimerCountDownWidget extends StatefulWidget {
    
    
  Function onTimerFinish;

  TimerCountDownWidget({
    
    this.onTimerFinish}) : super();

  @override
  State<StatefulWidget> createState() => 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;
          });
          //开始倒计时
          startCountdownTimer();
        }
      },
      child: RaisedButton(
        color: Colors.black12,
        child: Text(
          _countdownTime > 0 ? '$_countdownTime后重新获取' : '获取验证码',
          style: TextStyle(
            fontSize: 14,
            color: _countdownTime > 0
                ? Colors.white
                : Color.fromARGB(255, 17, 132, 255),
          ),
        ),
      ),
    );
  }

  void startCountdownTimer() {
    
    
//    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() {
    
    
    super.dispose();
    if (_timer != null) {
    
    
      _timer.cancel();
    }
  }
}

Use it as a Widget in the 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
 * @date   2020-02-28.
 */

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

class VerficationCodePageState extends State<VerficationCodePage> {
    
    
  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: Text("验证码倒计时"),
        centerTitle: true,
      ),
      body: Center(
        child: TimerCountDownWidget(onTimerFinish: (){
    
    
          print("倒计时结束--------");
        },),
      ),
    );
  }
}

After running the code, we click the Get Verification Code button. When the countdown ends, the callback function we passed in will be called. As shown below, the content we entered in the program is printed on the log console:

Insert image description here

Code related to this blog post: Blog post source code

Guess you like

Origin blog.csdn.net/xieluoxixi/article/details/104552521
Recommended