Flutter倒计时功能插件smart_countdown的使用

Flutter倒计时功能插件smart_countdown的使用

倒计时插件

一个用于在Flutter应用中显示可自定义的倒计时定时器的小部件。该插件支持文本定制、颜色选项,并且每秒自动刷新。

示例

MacOS

MacOS

Web

Web

IOS

IOS

特性

  • 显示倒计时定时器。
  • 可定制的文本样式和颜色。
  • 可以隐藏零值(如天数、小时数、分钟数和秒数)。
  • 跨平台支持Android、iOS、Web、macOS、Linux和Windows。

目录

安装

在你的pubspec.yaml文件的dependencies部分添加以下行:

dependencies:
  smart_countdown: ^1.0.0

然后运行以下命令:

flutter pub get

本地开发

如果你正在本地开发此插件(例如,在开发过程中),请添加路径到插件:

dependencies:
  smart_countdown:
    path: ../smart_countdown

使用

要将插件用于你的Flutter应用,请导入包并使用CountdownWidget小部件:

import 'package:smart_countdown/smart_countdown.dart';

class MyHomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    DateTime endDate = DateTime.now().add(Duration(days: 1, hours: 5));

    return Scaffold(
      appBar: AppBar(
        title: Text("Countdown Timer Example"),
      ),
      body: Center(
        child: CountdownWidget(
          endDate,
          completedText: "Countdown Complete!",
          timerStyle: TextStyle(fontSize: 18, color: Colors.blue),
          hideZeroValues: true,
        ),
      ),
    );
  }
}

CountdownWidget 参数

参数 类型 默认值 描述
endDate DateTime 必须 倒计时结束的日期和时间。
completedText String? "Time Completed!" 倒计时结束后显示的文本。
timerStyle TextStyle? null 应用于倒计时文本的样式(字体大小、粗细等)。
timerColor Color? Colors.grey 倒计时文本的颜色。
hideZeroValues bool? false 如果为true,则隐藏零值(如小时、分钟等)。

自定义选项

  1. completedText: 此参数允许你设置倒计时结束时的自定义文本。例如:

    completedText: "Event Started!"
    
  2. timerStyle: 通过传递TextStyle来自定义倒计时文本的外观:

    timerStyle: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.red)
    
  3. timerColor: 使用timerColor参数更改倒计时文本的颜色:

    timerColor: Colors.blueAccent
    
  4. hideZeroValues: 如果你想在某个部分达到零时隐藏它们(例如隐藏00 Days),可以将hideZeroValues设置为true

    hideZeroValues: true
    

示例

基本倒计时定时器

import 'package:flutter/material.dart';
import 'package:smart_countdown/smart_countdown.dart';

class CountdownPage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    DateTime endDate = DateTime.now().add(Duration(days: 1, hours: 5));

    return Scaffold(
      appBar: AppBar(
        title: Text("Basic Countdown Timer"),
      ),
      body: Center(
        child: CountdownWidget(
          endDate,
        ),
      ),
    );
  }
}

自定义倒计时定时器

import 'package:flutter/material.dart';
import 'package:smart_countdown/smart_countdown.dart';

class CustomCountdownPage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    DateTime endDate = DateTime.now().add(Duration(hours: 2, minutes: 45));

    return Scaffold(
      appBar: AppBar(
        title: Text("Customized Countdown Timer"),
      ),
      body: Center(
        child: CountdownWidget(
          endDate,
          completedText: "Countdown Complete!",
          timerStyle: const TextStyle(fontSize: 18, color: Colors.red),
          timerColor: Colors.red,
          hideZeroValues: true,
        ),
      ),
    );
  }
}

带有天数的倒计时定时器

import 'package:flutter/material.dart';
import 'package:smart_countdown/smart_countdown.dart';

class DaysCountdownPage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    DateTime endDate = DateTime.now().add(Duration(days: 7));

    return Scaffold(
      appBar: AppBar(
        title: Text("Countdown Timer with Days"),
      ),
      body: Center(
        child: CountdownWidget(
          endDate,
          completedText: "Countdown Complete!",
          timerStyle: const TextStyle(fontSize: 18, color: Colors.red),
          timerColor: Colors.red,
          hideZeroValues: true,
        ),
      ),
    );
  }
}

更多关于Flutter倒计时功能插件smart_countdown的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter倒计时功能插件smart_countdown的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 smart_countdown 插件在 Flutter 中实现倒计时功能的代码示例。smart_countdown 插件提供了一个简洁的方法来管理和显示倒计时。

首先,确保你的 Flutter 项目中已经添加了 smart_countdown 依赖。在 pubspec.yaml 文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  smart_countdown: ^x.y.z  # 请替换为最新版本号

然后运行 flutter pub get 以安装依赖。

接下来,在你的 Dart 文件中使用 smart_countdown 插件。以下是一个完整的示例,展示如何使用该插件来实现一个简单的倒计时功能:

import 'package:flutter/material.dart';
import 'package:smart_countdown/smart_countdown.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Countdown Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CountdownScreen(),
    );
  }
}

class CountdownScreen extends StatefulWidget {
  @override
  _CountdownScreenState createState() => _CountdownScreenState();
}

class _CountdownScreenState extends State<CountdownScreen> with SingleTickerProviderStateMixin {
  CountdownController _countdownController;

  @override
  void initState() {
    super.initState();
    // 初始化倒计时控制器,设置初始倒计时时间为10秒
    _countdownController = CountdownController(
      endTime: DateTime.now().add(Duration(seconds: 10)),
      interval: Duration(seconds: 1),
    );

    // 监听倒计时结束事件
    _countdownController.onEnd.listen((_) {
      print('Countdown ended!');
      // 可以在这里执行倒计时结束后的操作,比如显示一个消息
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Countdown ended!')));
    });

    // 开始倒计时
    _countdownController.start();
  }

  @override
  void dispose() {
    // 释放资源,停止倒计时
    _countdownController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Countdown Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Time remaining: ${_formatDuration(_countdownController.remainingTime)}',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _countdownController.isActive
                  ? () {
                      // 如果倒计时正在运行,则暂停
                      _countdownController.pause();
                    }
                  : () {
                      // 如果倒计时已暂停或结束,则开始或继续
                      if (!_countdownController.isEnded) {
                        _countdownController.resume();
                      }
                    },
              child: Text(_countdownController.isActive ? 'Pause' : 'Resume'),
            ),
          ],
        ),
      ),
    );
  }

  // 格式化剩余时间显示
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    return '${twoDigits(duration.inMinutes % 60)}:${twoDigits(duration.inSeconds % 60)}';
  }
}

代码解释:

  1. 依赖添加:在 pubspec.yaml 中添加 smart_countdown 依赖。
  2. 初始化倒计时控制器:在 initState 方法中初始化 CountdownController,并设置初始倒计时时间和更新间隔。
  3. 监听倒计时结束事件:使用 onEnd.listen 方法监听倒计时结束事件,当倒计时结束时显示一个 SnackBar。
  4. 开始倒计时:调用 _countdownController.start() 方法开始倒计时。
  5. 释放资源:在 dispose 方法中调用 _countdownController.dispose() 方法释放资源。
  6. UI 显示:使用 Text 组件显示剩余时间,并使用 ElevatedButton 组件控制倒计时的暂停和继续。
  7. 格式化时间_formatDuration 方法用于将 Duration 对象格式化为 MM:SS 格式的字符串。

这段代码展示了如何使用 smart_countdown 插件实现一个简单的倒计时功能,包括倒计时的开始、暂停、继续和结束处理。

回到顶部