Flutter倒计时进度指示器插件countdown_progress_indicator的使用

发布于 1周前 作者 yibo5220 来自 Flutter

Flutter倒计时进度指示器插件countdown_progress_indicator的使用

Countdown Progress Indicator

GitHub latest tag GitHub stars GitHub license

countdown_progress_indicator是一个为Flutter提供的可定制化倒计时进度指示器。

Getting Started

要在项目中使用此插件,首先需要在pubspec.yaml文件中添加依赖:

dependencies:
  ...
  countdown_progress_indicator: ^0.1.2

然后,在Dart代码中导入此包:

import 'package:countdown_progress_indicator/countdown_progress_indicator.dart';

How to use

CountDownProgressIndicator小部件默认情况下会自动开始倒计时,并且支持暂停和恢复操作。如果要实现这些功能,则需要使用CountdownController来控制。下面是一个简单的例子,它创建了一个20秒的倒计时进度指示器:

SizedBox(
  height: 200,
  width: 200,
  child: CountDownProgressIndicator(
    controller: _controller, // 使用控制器
    valueColor: Colors.red, // 进度条颜色
    backgroundColor: Colors.blue, // 背景颜色
    initialPosition: 0, // 初始位置
    duration: 20, // 倒计时时长(秒)
    text: 'SEC', // 显示文本
    onComplete: () => null, // 完成后的回调
  ),
),

Custom Formatter

如果你想要显示不同于秒数的文字,可以实现自定义的时间格式化器。例如,将时间格式化为hh:mm:ss的形式:

CountDownProgressIndicator(
  controller: _controller,
  valueColor: Colors.red,
  backgroundColor: Colors.blue,
  initialPosition: 0,
  duration: 365,
  timeFormatter: (seconds) {
    return Duration(seconds: seconds)
        .toString()
        .split('.')[0]
        .padLeft(8, '0');
  },
  text: 'hh:mm:ss',
  onComplete: () => null,
),

示例demo

以下是一个完整的示例应用,展示了如何使用countdown_progress_indicator包创建两个倒计时进度指示器,并提供了暂停/继续按钮来控制它们:

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

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isRunning = true;
  final _controller = CountDownController();
  final _controller2 = CountDownController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          color: Colors.white,
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  height: 200,
                  width: 200,
                  child: CountDownProgressIndicator(
                    controller: _controller,
                    valueColor: Colors.red,
                    backgroundColor: Colors.blue,
                    initialPosition: 0,
                    duration: 365,
                    timeFormatter: (seconds) {
                      return Duration(seconds: seconds)
                          .toString()
                          .split('.')[0]
                          .padLeft(8, '0');
                    },
                    text: 'hh:mm:ss',
                    onComplete: () => null,
                  ),
                ),
                const SizedBox(height: 20),
                SizedBox(
                  height: 200,
                  width: 200,
                  child: CountDownProgressIndicator(
                    controller: _controller2,
                    valueColor: Colors.red,
                    backgroundColor: Colors.blue,
                    initialPosition: 0,
                    duration: 365,
                    text: 'Seg',
                    onComplete: () => null,
                  ),
                ),
                const SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () => setState(() {
                    if (_isRunning) {
                      _controller.pause();
                      _controller2.pause();
                    } else {
                      _controller.resume();
                      _controller2.resume();
                    }

                    _isRunning = !_isRunning;
                  }),
                  child: Text(_isRunning ? 'Pause' : 'Resume'),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

这个示例程序创建了两个倒计时进度指示器,每个都设置为365秒(即6分钟零5秒),并且提供了一个按钮用于暂停或恢复所有倒计时。通过点击按钮,用户可以在运行和暂停状态之间切换。


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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用countdown_progress_indicator插件的代码示例。这个插件可以用来创建一个倒计时进度指示器,非常适合用于需要显示倒计时进度的场景,比如计时器、考试倒计时等。

首先,确保你已经在pubspec.yaml文件中添加了countdown_progress_indicator依赖:

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

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

接下来,在你的Dart文件中使用CountdownProgressIndicator。以下是一个完整的示例代码:

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

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

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

class CountdownPage extends StatefulWidget {
  @override
  _CountdownPageState createState() => _CountdownPageState();
}

class _CountdownPageState extends State<CountdownPage> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  final int _endTime = DateTime.now().millisecondsSinceEpoch + 10000; // 10秒后结束

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(milliseconds: _endTime - DateTime.now().millisecondsSinceEpoch),
      vsync: this,
    )..repeat(reverse: true);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double progress = (_endTime - DateTime.now().millisecondsSinceEpoch).toDouble() / _endTime;
    progress = progress.clamp(0.0, 1.0); // 确保进度在0到1之间

    return Scaffold(
      appBar: AppBar(
        title: Text('Countdown Progress Indicator Demo'),
      ),
      body: Center(
        child: CountdownProgressIndicator(
          animation: Tween<double>(begin: 0.0, end: 1.0).animate(_controller),
          strokeWidth: 5.0,
          color: Colors.blue,
          backgroundColor: Colors.grey[200]!,
          radius: 30.0,
          percentage: progress * 100,
          period: _endTime ~/ 1000, // 总秒数
          secondsBuilder: (context, count, period, remainingPeriod) {
            return Text(
              '${remainingPeriod.inSeconds}s',
              style: TextStyle(fontSize: 20),
            );
          },
          child: Center(
            child: Text(
              '倒计时',
              style: TextStyle(fontSize: 24, color: Colors.white),
            ),
          ),
        ),
      ),
    );
  }
}

在这个示例中:

  1. 我们创建了一个CountdownPage页面,它包含了一个CountdownProgressIndicator
  2. AnimationController用于控制动画,它的持续时间设置为从当前时间到10秒后的时间。
  3. Tween<double>(begin: 0.0, end: 1.0).animate(_controller)用于创建动画,动画的值从0到1。
  4. progress变量计算当前的进度比例,并限制在0到1之间。
  5. CountdownProgressIndicatorpercentage属性设置为当前的进度百分比。
  6. secondsBuilder回调用于显示剩余的秒数。

这个示例展示了如何使用countdown_progress_indicator插件来创建一个简单的倒计时进度指示器,并显示剩余的秒数。你可以根据实际需求调整动画的持续时间、样式等属性。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!