使用getX写一个最简单的倒计时

1,018 阅读1分钟

需求  

  • 倒计时10秒消失对话框,10s内不能关闭。
  • 10秒后对话框可以点击消失

最终效果如下

 

实现

   Timer+GetX

  controller代码  

``` /**    author:mac    创建日期:2021/11/23    描述: */import 'dart:async';import 'package:flutter/material.dart';import 'package:get/get.dart';class AuthDialogController extends GetxController {  RxInt count = RxInt(10);  var text =      '我们重视用户的隐私。您在使用我们的服务时,我们可能会收集和使用您的相关信息。\n 我们希望通过本《隐私政策》向您说明,\n  在使用我们的服务时,我们如何收集、使用、储存和分享这些信息,以及我们为您提供的访问、更新、控制和保护这些信息的方式。本《隐私政策》与您所使用的服务息息相关,希望您仔细阅读,在需要时,按照本《隐私政策》的指引,作出您认为适当的选择。本《隐私政策》中涉及的相关技术词汇,我们尽量以简明扼要的表述,并提供进一步说明的链接,以便您的理解您使用或继续使用我们的服务,即意味着同意我们按照本《隐私政策》收集、使用、储存和分享您的相关信息。如对本《隐私政策》或相关事宜有任何问题,请通过yeyuanshen@128xy.com与我们联系。我们可能收集的信息我们提供服务时,可能会收集、储存和使用下列与您有关的信息。如果您不提供相关信息,可能无法享受我们提供的某些服务,或者无法达到相关服务拟达到的效果。';  Timer _timer;  init() {    print('init  $count');    count.value = 10;    _timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {      if (count.value >= 1) {        count.value -= 1;      } else {        // 倒计时结束        print('倒计时结束了');        _timer.cancel();      }    });  }  dismiss(BuildContext context) {    Navigator.of(context).pop();  }  @override  void dispose() {    Get.delete<AuthDialogController>();    _timer.cancel();    super.dispose();  }}```

```

dialog代码

 /**    author:mac    创建日期:2021/11/23    描述: */import 'package:flutter/material.dart';import 'package:get/get.dart';import 'package:getx_pattern/app/ui/android/widgets/dialog_auth/controller.dart';class AuthDialog extends StatefulWidget {  const AuthDialog({Key key}) : super(key: key);  @override  _AuthDialogState createState() => _AuthDialogState();}class _AuthDialogState extends State<AuthDialog> {  AuthDialogController controller = Get.put(AuthDialogController());  @override  void initState() {    super.initState();    controller.init();  }  @override  Widget build(BuildContext context) {    return SimpleDialog(      title: Text('用户需知'),      children: [        Padding(          padding: EdgeInsets.all(10),          child: Text(controller.text),        ),        Obx(() => Padding(              child: ElevatedButton(                  child: Text('我知道了,倒计时 剩余(${controller.count.value}) s'),                  onPressed: _btnClick()),              padding: EdgeInsets.all(10),            ))      ],    );  }  _btnClick() {    if (controller.count.value >= 1) {      return null;    } else {      return () {        controller.dismiss(context);      };    }  }}