Flutter计时器功能插件simple_timer的使用

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

Flutter 计时器功能插件 simple_timer 的使用

简介

SimpleTimer 是一个简单的计时器小部件,可以显示带有各种可自定义选项的计时器进度。

安装

要开始使用此库,请在 pubspec.yaml 文件中包含 simple_timer 作为依赖项。确保使用最新版本。

dependencies:
  simple_timer: ^x.x.x

使用

要使用该小部件,请在项目中导入包:

import 'package:simple_timer/simple_timer.dart';

计时器可以通过两种方式控制:

使用 TimerController(推荐)

TimerController 是一个方便的包装器(子类)的 AnimationController,并且需要一个 TickerProvider,因此请确保扩展 TickerProvider 类。

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  TimerController _timerController;

  @override
  void initState() {
    // 初始化计时器控制器
    _timerController = TimerController(this);
    super.initState();
  }

  @override
  void dispose() {
    // 释放资源
    _timerController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Expanded(
              child: Container(
                margin: EdgeInsets.symmetric(vertical: 10),
                child: SimpleTimer(
                  controller: _timerController,
                  duration: const Duration(seconds: 5),
                  timerStyle: TimerStyle.ring,
                  backgroundColor: Colors.grey,
                  progressIndicatorColor: Colors.green,
                  progressIndicatorDirection: TimerProgressIndicatorDirection.clockwise,
                  progressTextCountDirection: TimerProgressTextCountDirection.count_down,
                  progressTextStyle: TextStyle(color: Colors.black),
                  strokeWidth: 10,
                ),
              ),
            ),
            Column(
              children: <Widget>[
                Text("Timer Status", style: TextStyle(fontWeight: FontWeight.bold)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    TextButton(
                      onPressed: _timerController.start,
                      child: Text("Start"),
                      style: TextButton.styleFrom(backgroundColor: Colors.green),
                    ),
                    TextButton(
                      onPressed: _timerController.pause,
                      child: Text("Pause"),
                      style: TextButton.styleFrom(backgroundColor: Colors.blue),
                    ),
                    TextButton(
                      onPressed: _timerController.reset,
                      child: Text("Reset"),
                      style: TextButton.styleFrom(backgroundColor: Colors.red),
                    ),
                    TextButton(
                      onPressed: _timerController.restart,
                      child: Text("Restart"),
                      style: TextButton.styleFrom(backgroundColor: Colors.orange),
                    ),
                  ],
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}

设置状态

计时器也可以通过传递 TimerStatus 值来控制状态,例如:

Container(
  child: SimpleTimer(
    status: TimerStatus.start,
    duration: Duration(seconds: 10),
  )
)

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

1 回复

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


当然,以下是如何在Flutter项目中使用simple_timer插件来实现计时器功能的示例代码。

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

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

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

接下来,我们编写一个Flutter应用来展示如何使用simple_timer插件。这个示例将包括一个按钮来启动和停止计时器,并在屏幕上显示经过的时间。

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

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

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

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

class _TimerScreenState extends State<TimerScreen> with SingleTickerProviderStateMixin {
  late TimerController _timerController;
  String _elapsedTime = '00:00:00';
  bool _isRunning = false;

  @override
  void initState() {
    super.initState();
    _timerController = TimerController();
    _timerController.ticker.listen((duration) {
      setState(() {
        _elapsedTime = _formatDuration(duration);
      });
    });
  }

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

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padStart(2, '0');
    int hours = duration.inHours;
    int minutes = duration.inMinutes % 60;
    int seconds = duration.inSeconds % 60;
    return '${twoDigits(hours)}:${twoDigits(minutes)}:${twoDigits(seconds)}';
  }

  void _toggleTimer() {
    setState(() {
      _isRunning = !_isRunning;
      if (_isRunning) {
        _timerController.start();
      } else {
        _timerController.stop();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Simple Timer Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _elapsedTime,
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _toggleTimer,
              child: Text(_isRunning ? 'Stop' : 'Start'),
            ),
          ],
        ),
      ),
    );
  }
}

解释

  1. 依赖管理:在pubspec.yaml中添加simple_timer依赖。
  2. 初始化TimerController:在initState方法中初始化TimerController并监听其ticker事件,每当计时器更新时,UI会重新渲染显示新的时间。
  3. 格式化时间_formatDuration方法用于将Duration对象格式化为HH:MM:SS格式的字符串。
  4. 启动和停止计时器_toggleTimer方法用于切换计时器的运行状态。如果计时器正在运行,则停止它;如果计时器已停止,则启动它。
  5. UI:在UI中显示经过的时间,并提供一个按钮来启动和停止计时器。

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

回到顶部