Flutter计时器插件timer_stop_watch的使用

Flutter计时器插件timer_stop_watch的使用

你可以自由地使用一个计时器和一个秒表。

安装

在你的包的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  timer_stop_watch:

然后运行 flutter pub get 来获取依赖项。

使用

首先,你需要导入 timer_stop_watch 包并创建一个 TimerStopWatch 实例。然后,你可以初始化计时器和秒表,并通过 StreamBuilder 来监听它们的状态变化。

import 'package:timer_stop_watch/timer_stop_watch.dart';  // 导入 timer_stop_watch

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _timerStopWatch = TimerStopWatch(); // 创建 timer_stop_watch 实例。
  late Stream<String> _timer; // 创建一个计时器变量。
  late Stream<String> _stopwatch; // 创建一个秒表变量。

  [@override](/user/override)
  void initState() {
    super.initState();
    _timer = _timerStopWatch.setTimer(hour: 1, minute: 1, seconds: 10, timeFormat: "hh:mm:ss");  // 计时器初始化
    _stopwatch = _timerStopWatch.setStopwatch(timeFormat: "hh:mm:ss");  // 秒表初始化
  }

  [@override](/user/override)
  void dispose() {
    _timerStopWatch.dispose();  // 需要调用 dispose 函数。
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('计时器与秒表'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
          StreamBuilder(
            stream: _timer,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.toString()); // 显示计时器时间
              } else if (snapshot.hasError) {
                print(snapshot.error);
                return SizedBox();
              } else {
                return CircularProgressIndicator(); // 加载指示器
              }
            }),
          SizedBox(height: 20),
          StreamBuilder(
            stream: _stopwatch,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.toString()); // 显示秒表时间
              } else if (snapshot.hasError) {
                print(snapshot.error);
                return SizedBox();
              } else {
                return CircularProgressIndicator(); // 加载指示器
              }
            }),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: () {_timerStopWatch.startTimer();}, // 启动计时器
            child: Text("启动计时器"),
          ),
          SizedBox(height: 10),
          ElevatedButton(
            onPressed: () {_timerStopWatch.startStopwatch();}, // 启动秒表
            child: Text("启动秒表"),
          ),
          SizedBox(height: 10),
          ElevatedButton(
            onPressed: () {_timerStopWatch.pauseTimer();}, // 暂停计时器
            child: Text("暂停计时器"),
          ),
          SizedBox(height: 10),
          ElevatedButton(
            onPressed: () {_timerStopWatch.pauseStopwatch();}, // 暂停秒表
            child: Text("暂停秒表"),
          ),
          SizedBox(height: 10),
          ElevatedButton(
            onPressed: () {_timerStopWatch.resetTimer();}, // 重置计时器
            child: Text("重置计时器"),
          ),
          SizedBox(height: 10),
          ElevatedButton(
            onPressed: () {_timerStopWatch.resetStopwatch();}, // 重置秒表
            child: Text("重置秒表"),
          ),
        ],
      ),
    );
  }
}

示例代码

下面是完整的示例代码,展示了如何使用 timer_stop_watch 插件来实现多个计时器和秒表的功能。

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'TimerStopwatch',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const TimerPage(),
    );
  }
}

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

  [@override](/user/override)
  State<TimerPage> createState() => _TimerPageState();
}

class _TimerPageState extends State<TimerPage> {
  final _timerStopWatch = TimerStopWatch();
  late Stream<String> _timer1;
  late Stream<String> _timer2;
  late Stream<String> _timer3;
  late Stream<String> _stopwatch1;
  late Stream<String> _stopwatch2;
  late Stream<String> _stopwatch3;

  [@override](/user/override)
  void initState() {
    super.initState();
    _timer1 = _timerStopWatch.setTimer(hour: 1, minute: 1, seconds: 10, timeFormat: "hh:mm:ss", start: true);
    _timer2 = _timerStopWatch.setTimer(hour: 1, minute: 1, seconds: 10, start: true);
    _timer3 = _timerStopWatch.setTimer(hour: 1, minute: 1, seconds: 10, timeFormat: "hh:mm:ss", key: "timer3");

    _stopwatch1 = _timerStopWatch.setStopwatch(start: true, timeFormat: "hh:mm:ss");
    _stopwatch2 = _timerStopWatch.setStopwatch(start: true);
    _stopwatch3 = _timerStopWatch.setStopwatch(timeFormat: "hh:mm:ss", key: "stopwatch3");
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Padding(
          padding: const EdgeInsets.only(top: 8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(
                width: MediaQuery.of(context).size.width * 0.45,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Spacer(),
                    Text("Timer", style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                    Divider(thickness: 1),
                    StreamBuilder(
                        stream: _timer1,
                        builder: (context, snapshot) {
                          if (snapshot.hasData) {
                            return Text(snapshot.data.toString());
                          } else if (snapshot.hasError) {
                            print(snapshot.error);
                            return SizedBox();
                          } else {
                            return CircularProgressIndicator();
                          }
                        }),
                    StreamBuilder(
                        stream: _timer2,
                        builder: (context, snapshot) {
                          if (snapshot.hasData) {
                            return Text(snapshot.data.toString());
                          } else if (snapshot.hasError) {
                            print(snapshot.error);
                            return SizedBox();
                          } else {
                            return CircularProgressIndicator();
                          }
                        }),
                    SizedBox(height: 30),
                    StreamBuilder(
                        stream: _timer3,
                        builder: (context, snapshot) {
                          if (snapshot.hasData) {
                            return Text(snapshot.data.toString());
                          } else if (snapshot.hasError) {
                            print(snapshot.error);
                            return SizedBox();
                          } else {
                            return CircularProgressIndicator();
                          }
                        }),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ElevatedButton(
                          onPressed: () {
                            _timerStopWatch.startTimer(key: "timer3");
                          },
                          child: Text("start"),
                          style: ElevatedButton.styleFrom(minimumSize: Size.zero, padding: EdgeInsets.all(5))
                        ),
                        ElevatedButton(
                            onPressed: () {
                              _timerStopWatch.pauseTimer(key: "timer3");
                            },
                            child: Text("pause"),
                            style: ElevatedButton.styleFrom(minimumSize: Size.zero, padding: EdgeInsets.all(5))
                        ),
                        ElevatedButton(
                            onPressed: () {
                              _timerStopWatch.resetTimer(key: "timer3");
                            },
                            child: Text("reset"),
                            style: ElevatedButton.styleFrom(minimumSize: Size.zero, padding: EdgeInsets.all(5))
                        ),
                      ],
                    ),
                    SizedBox(height: 30),
                    ElevatedButton(
                        onPressed: (){_timerStopWatch.startTimer();},
                        child: Text("all start")),
                    ElevatedButton(
                        onPressed: (){_timerStopWatch.pauseTimer();},
                        child: Text("all pause")),
                    ElevatedButton(
                        onPressed: (){_timerStopWatch.resetTimer();},
                        child: Text("all reset")),
                    Spacer(),
                  ],
                ),
              ),
              VerticalDivider(
                thickness: 1,
              ),
              SizedBox(
                width: MediaQuery.of(context).size.width * 0.45,
                child: Column(
                  children: [
                    Spacer(),
                    Text(
                      "Stopwatch",
                      style:
                          TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                    ),
                    Divider(
                      thickness: 1,
                    ),
                    StreamBuilder(
                        stream: _stopwatch1,
                        builder: (context, snapshot) {
                          if (snapshot.hasData) {
                            return Text(snapshot.data.toString());
                          } else if (snapshot.hasError) {
                            print(snapshot.error);
                            return SizedBox();
                          } else {
                            return CircularProgressIndicator();
                          }
                        }),
                    StreamBuilder(
                        stream: _stopwatch2,
                        builder: (context, snapshot) {
                          if (snapshot.hasData) {
                            return Text(snapshot.data.toString());
                          } else if (snapshot.hasError) {
                            print(snapshot.error);
                            return SizedBox();
                          } else {
                            return CircularProgressIndicator();
                          }
                        }),
                    SizedBox(height: 30),
                    StreamBuilder(
                        stream: _stopwatch3,
                        builder: (context, snapshot) {
                          if (snapshot.hasData) {
                            return Text(snapshot.data.toString());
                          } else if (snapshot.hasError) {
                            print(snapshot.error);
                            return SizedBox();
                          } else {
                            return CircularProgressIndicator();
                          }
                        }),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ElevatedButton(
                            onPressed: () {
                              _timerStopWatch.startStopwatch(key: "stopwatch3");
                            },
                            child: Text("start"),
                            style: ElevatedButton.styleFrom(minimumSize: Size.zero, padding: EdgeInsets.all(5))
                        ),
                        ElevatedButton(
                            onPressed: () {
                              _timerStopWatch.pauseStopwatch(key: "stopwatch3");
                            },
                            child: Text("pause"),
                            style: ElevatedButton.styleFrom(minimumSize: Size.zero, padding: EdgeInsets.all(5))
                        ),
                        ElevatedButton(
                            onPressed: () {
                              _timerStopWatch.resetStopwatch(key: "stopwatch3");
                            },
                            child: Text("reset"),
                            style: ElevatedButton.styleFrom(minimumSize: Size.zero, padding: EdgeInsets.all(5))
                        ),
                      ],
                    ),
                    SizedBox(height: 30),
                    ElevatedButton(
                        onPressed: (){_timerStopWatch.startStopwatch();},
                        child: Text("all start")),
                    ElevatedButton(
                        onPressed: (){_timerStopWatch.pauseStopwatch();},
                        child: Text("all pause")),
                    ElevatedButton(
                        onPressed: (){_timerStopWatch.resetStopwatch();},
                        child: Text("all reset")),
                    Spacer(),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  [@override](/user/override)
  void dispose() {
    _timerStopWatch.dispose();
    super.dispose();
  }
}

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

1 回复

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


当然,以下是如何在Flutter中使用timer_stop_watch插件来实现一个简单计时器功能的代码示例。首先,你需要在你的pubspec.yaml文件中添加该插件的依赖:

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

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

接下来是一个简单的Flutter应用示例,展示如何使用timer_stop_watch插件来创建一个计时器:

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

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

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

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

class _TimerScreenState extends State<TimerScreen> with SingleTickerProviderStateMixin {
  TimerStopWatch _timerStopWatch = TimerStopWatch();
  String _timeDisplay = "00:00:00";
  bool _isRunning = false;

  @override
  void initState() {
    super.initState();
    _timerStopWatch.onTick.listen((event) {
      setState(() {
        _timeDisplay = _formatTime(event.elapsedMilliseconds);
      });
    });
  }

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

  String _formatTime(int milliseconds) {
    int seconds = (milliseconds / 1000).toInt();
    int minutes = (seconds / 60).toInt();
    int hours = (minutes / 60).toInt();

    seconds = seconds % 60;
    minutes = minutes % 60;

    return String.format("%02d:%02d:%02d", hours, minutes, seconds);
  }

  void _startTimer() {
    if (!_isRunning) {
      _timerStopWatch.start();
      setState(() {
        _isRunning = true;
      });
    }
  }

  void _pauseTimer() {
    if (_isRunning) {
      _timerStopWatch.pause();
      setState(() {
        _isRunning = false;
      });
    }
  }

  void _resetTimer() {
    _timerStopWatch.reset();
    setState(() {
      _timeDisplay = "00:00:00";
      _isRunning = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Timer Stop Watch Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _timeDisplay,
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                ElevatedButton(
                  onPressed: _startTimer,
                  child: Text('Start'),
                  style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.green),
                  ),
                ),
                SizedBox(width: 20),
                ElevatedButton(
                  onPressed: _pauseTimer,
                  child: Text('Pause'),
                  style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.amber),
                  ),
                ),
                SizedBox(width: 20),
                ElevatedButton(
                  onPressed: _resetTimer,
                  child: Text('Reset'),
                  style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.red),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个包含三个按钮(Start、Pause、Reset)的简单计时器界面。我们使用TimerStopWatch插件来管理计时器的状态,并在计时器更新时更新显示的时间。

  • _startTimer 方法用于启动计时器。
  • _pauseTimer 方法用于暂停计时器。
  • _resetTimer 方法用于重置计时器。

_formatTime 方法用于将毫秒转换为格式化的时间字符串(小时:分钟:秒)。

确保你已经在项目中正确添加了timer_stop_watch插件的依赖,并且已经运行了flutter pub get。这个示例应该能帮助你快速上手使用timer_stop_watch插件来实现计时器功能。

回到顶部