Flutter可暂停计时器插件pausable_timer的使用

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

Flutter可暂停计时器插件pausable_timer的使用

简介

pausable_timer 是一个Dart库,提供了可以暂停、恢复和重置的定时器功能。这个库非常适合需要精确控制时间的应用场景,比如游戏开发中的倒计时、任务调度等。

安装

pubspec.yaml 文件中添加依赖:

dependencies:
  pausable_timer: ^latest_version # 替换为最新版本号

然后运行 flutter pub get 来安装包。

示例代码

基本用法

下面是一个简单的例子,演示了如何创建、启动、暂停、恢复和取消一个定时器:

import 'package:pausable_timer/pausable_timer.dart';

void main() async {
  print('Create a timer that fires in 1 second, but it is not started yet');
  final timer = PausableTimer(Duration(seconds: 1), () => print('Fired!'));
  print('So we start it');
  timer.start();

  print('And wait 1/2 second...');
  await Future<void>.delayed(timer.duration ~/ 2);
  print('Not yet fired, still 1/2 second to go!');

  print('We can pause it now');
  timer.pause();

  // When paused, time can pass but the timer won't be fired
  print('And we wait a whole second...');
  await Future<void>.delayed(timer.duration);
  print("But our timer doesn't care while it's paused");
  print('It will still wait for ${timer.duration - timer.elapsed} after '
      "it's started again");

  print('So we start it again');
  timer.start();
  print('And wait for 1/2 second again, it should have fired when we are done');
  await Future<void>.delayed(timer.duration ~/ 2);
  print('And we are done, "Fired!" should be up there 👆');
  print('Now our timer completed ${timer.tick} tick');

  print('We can reset it if we want to use it again');
  timer.reset();
  print('We have to start it again after the reset because it was not running');
  timer.start();
  print('Now we wait a whole second in one go...');
  await Future<void>.delayed(timer.duration);
  print('And we are done, so you should see "Fired!" up there again 👆');
  print('Now the timer has ${timer.tick} ticks');

  print('We can reset it and start it again');
  timer.reset();
  timer.start();

  print('And you can cancel it too, so it will not fire again');
  timer.cancel();
  print("After a timer is cancelled, it can't be used again");
  print('But important information can still be retrieved:');
  print('duration: ${timer.duration}');
  print('elapsed: ${timer.elapsed}');
  print('tick: ${timer.tick}');
  print('isPaused: ${timer.isPaused}');
  print('isActive: ${timer.isActive}');
  print('isExpired: ${timer.isExpired}');
  print('isCancelled: ${timer.isCancelled}');
}

倒计时实现

接下来是一个更复杂的例子,展示了如何使用 PausableTimer.periodic 实现一个可以暂停的倒计时:

import 'dart:async';
import 'package:pausable_timer/pausable_timer.dart';

void main() async {
  late final PausableTimer timer;
  var countDown = 5;

  print('Create a periodic timer that fires every 1 second and starts it');
  timer = PausableTimer.periodic(
    Duration(seconds: 1),
        () {
      countDown--;

      if (countDown == 0) {
        timer.pause();
      }

      print('\t$countDown');
    },
  )..start();

  print('And wait 2.1 seconds...');
  print('(0.1 extra to make sure there is no race between the timer and the '
      'waiting here)');
  await Future<void>.delayed(timer.duration * 2.1);
  print('By now 2 events should have fired: 4, 3\n');

  print('We can pause it now');
  timer.pause();

  print('And we wait for 2 more seconds...');
  await Future<void>.delayed(timer.duration * 2);
  print("But our timer doesn't care while it's paused\n");

  print('So we start it again');
  timer.start();
  print('And wait for 3.1 seconds more...');
  await Future<void>.delayed(timer.duration * 3.1);
  print('And we are done: 2, 1 and 0 should have been printed');

  print('The timer should be unpaused, inactive, expired and not cancelled');
  print('isPaused: ${timer.isPaused}');
  print('isActive: ${timer.isActive}');
  print('isExpired: ${timer.isExpired}');
  print('isCancelled: ${timer.isCancelled}');

  print('We can now reset it and start it again, now for 3 seconds');
  countDown = 3;
  timer
    ..reset()
    ..start();
  print('And wait for 3.1 seconds...');
  await Future<void>.delayed(timer.duration * 3.1);
  print('And it should be done printing: 2, 1 and 0');
}

总结

pausable_timer 提供了一种灵活的方式来管理定时器的行为,包括暂停、恢复和重置等功能。通过上述示例,您可以更好地理解如何在Flutter应用中使用这个强大的工具。希望这些信息对您有所帮助!如果有任何问题或需要进一步的帮助,请随时提问。


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

1 回复

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


当然,以下是如何在Flutter中使用pausable_timer插件来创建一个可暂停的计时器的示例代码。

首先,确保你已经将pausable_timer插件添加到你的pubspec.yaml文件中:

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

然后运行flutter pub get来安装该插件。

接下来是完整的示例代码,展示如何使用pausable_timer插件来创建一个可暂停和继续的计时器:

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

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

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

class TimerScreen extends StatefulWidget {
  @override
  _TimerScreenState createState() => _TimerScreenState();
}

class _TimerScreenState extends State<TimerScreen> with SingleTickerProviderStateMixin {
  late PausableTimerController _timerController;
  late int _elapsedSeconds = 0;
  bool _isPaused = false;

  @override
  void initState() {
    super.initState();
    _timerController = PausableTimerController(duration: const Duration(seconds: 60));
    _timerController.addListener(_updateTime);
    _timerController.start();
  }

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

  void _updateTime() {
    if (!_timerController.isPaused && !_timerController.isCompleted) {
      setState(() {
        _elapsedSeconds = _timerController.elapsed.inSeconds;
      });
    }
  }

  void _togglePause() {
    setState(() {
      _isPaused = !_isPaused;
      if (_isPaused) {
        _timerController.pause();
      } else {
        _timerController.resume();
      }
    });
  }

  void _resetTimer() {
    setState(() {
      _elapsedSeconds = 0;
      _isPaused = false;
      _timerController.reset();
      _timerController.start();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Pausable Timer Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Elapsed Time: ${_formatTime(_elapsedSeconds)}',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _togglePause,
              child: Text(_isPaused ? 'Resume' : 'Pause'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _resetTimer,
              child: Text('Reset'),
            ),
          ],
        ),
      ),
    );
  }

  String _formatTime(int seconds) {
    int minutes = seconds ~/ 60;
    int secs = seconds % 60;
    return "${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}";
  }
}

代码解释:

  1. 依赖导入

    • 导入flutterpausable_timer包。
  2. Main函数

    • 创建一个MaterialApp,设置标题和主题,并将TimerScreen作为主页面。
  3. TimerScreen组件

    • 创建一个有状态的Widget TimerScreen,并混合SingleTickerProviderStateMixin以使用计时器。
    • 初始化_timerControllerPausableTimerController,设置初始持续时间为60秒。
    • 监听计时器的变化,并更新已用时间。
    • 提供暂停/继续和重置按钮来控制计时器。
  4. 时间更新和格式化

    • _updateTime方法根据计时器的状态更新已用时间。
    • _formatTime方法将秒数格式化为MM:SS格式。
  5. 按钮事件

    • _togglePause方法用于暂停或继续计时器。
    • _resetTimer方法重置计时器到初始状态并重新开始。

这个示例展示了如何使用pausable_timer插件来创建一个基本的可暂停计时器应用。你可以根据需要进一步扩展和自定义此示例。

回到顶部