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

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

CountdownStream 包

CountdownStream 是一个用于 Dart 应用的简单高效的倒计时定时器包,提供了带有暂停、恢复、重置和销毁功能的倒计时流。

特性

  • 使用指定秒数启动倒计时定时器。
  • 可以在任何时间暂停和恢复倒计时。
  • 可以将倒计时定时器重置回初始持续时间。
  • 通过广播流监听倒计时更新。
  • 在完成、暂停、恢复、重置和销毁事件上执行操作。

开始使用

要使用此包,在 pubspec.yaml 文件中添加 countdown_stream 作为依赖项。

安装

dependencies:
  countdown_stream: ^0.0.1

然后运行以下命令来获取包:

pub get

如果你正在使用 Flutter:

flutter pub get

使用方法

在需要使用的地方导入该包:

import 'package:countdown_stream/countdown_stream.dart';

创建一个 CountdownStream 实例,监听倒计时滴答,并根据需要控制定时器:

final countdown = CountdownStream(initialSeconds: 10);

countdown.stream.listen((seconds) {
  print('$seconds 秒剩余');
});

countdown.startTimer();

// 暂停倒计时
countdown.pauseTimer();

// 恢复倒计时
countdown.resumeTimer();

// 重置倒计时
countdown.resetTimer();

// 不要忘记在完成后销毁倒计时流
countdown.dispose();

示例

void main() {
  final countdown = CountdownStream(initialSeconds: 10);

  countdown.stream.listen((seconds) {
    print('$seconds 秒剩余');
  });

  countdown.onComplete = () {
    print('倒计时完成!');
    countdown.dispose();
  };

  countdown.startTimer();
}

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

1 回复

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


当然,以下是如何在Flutter中使用countdown_stream插件来实现倒计时功能的代码示例。countdown_stream是一个用于创建和管理倒计时的Flutter插件。

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

dependencies:
  flutter:
    sdk: flutter
  countdown_stream: ^latest_version  # 请替换为最新版本号

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

接下来,下面是一个完整的Flutter应用示例,展示如何使用countdown_stream来实现一个简单的倒计时功能:

import 'package:flutter/material.dart';
import 'package:countdown_stream/countdown_stream.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> {
  CountdownController? _countdownController;
  String _timeRemaining = "00:00:00";

  @override
  void initState() {
    super.initState();
    // 初始化倒计时控制器,设置倒计时时间为60秒(1分钟)
    _countdownController = CountdownController.withDuration(Duration(seconds: 60));

    // 监听倒计时流的更新
    _countdownController!.stream!.listen((event) {
      // 更新剩余时间
      setState(() {
        _timeRemaining = event.remainingTime.toString().split('.').first;
      });

      // 倒计时结束时执行的操作
      if (event.isCompleted) {
        print("Countdown completed!");
        // 可选:重置倒计时或执行其他操作
        // _countdownController!.reset();
      }
    });

    // 开始倒计时
    _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(
              _timeRemaining,
              style: TextStyle(fontSize: 48),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // 暂停倒计时
                _countdownController?.pause();
              },
              child: Text('Pause'),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: () {
                // 如果倒计时已暂停,则恢复倒计时
                if (_countdownController!.isPaused) {
                  _countdownController?.resume();
                } else {
                  // 如果倒计时未暂停,则重置并重新开始倒计时
                  _countdownController?.reset();
                  _countdownController?.start();
                }
              },
              child: Text('Reset & Start'),
            ),
          ],
        ),
      ),
    );
  }
}

代码解释:

  1. 依赖导入:导入fluttercountdown_stream包。
  2. 应用入口MyApp是应用的入口,包含一个MaterialAppCountdownScreen作为首页。
  3. 倒计时屏幕CountdownScreen是一个有状态的组件,用于显示和控制倒计时。
  4. 初始化倒计时:在initState方法中,初始化CountdownController并设置倒计时的初始时间为60秒。
  5. 监听倒计时更新:通过listen方法监听倒计时流的更新,并在每次更新时调用setState方法更新UI。
  6. 控制倒计时:提供按钮来控制倒计时的暂停、重置和重新开始。
  7. 释放资源:在dispose方法中释放CountdownController资源。

这个示例展示了如何使用countdown_stream插件实现一个简单的倒计时功能,包括显示剩余时间、暂停和重置倒计时。你可以根据需要进一步定制和扩展这个示例。

回到顶部