首页 > 解决方案 > Flutter - 如何在 Flutter 中创建 30 分钟或任何后台计时器?

问题描述

大家好!

例如: 我想当用户单击按钮开始 30 分钟计时器和按钮禁用时。如果用户关闭应用程序但计时器没有停止它应该在后台工作我该如何创建这个系统?简而言之,当生命为 0 时,我希望它像糖果迷恋,然后在 1 小时的生命满 5 后启动 1 小时的后台计时器......

我在pub.dev上搜索,但找不到任何插件或包

标签: fluttertimerbackground-processcountdowntimer

解决方案


也许这对你有用 这也在应用程序处于后台时运行

import 'package:flutter/material.dart';
import 'dart:ui';
import 'dart:async';

void main() => runApp(MyApp());

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

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 TickerProviderStateMixin {

  AnimationController controller;

  Duration get duration => controller.duration * controller.value;

  bool get expired => duration.inSeconds == 0;

  @override
  void initState() {
    controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 30),
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            AnimatedBuilder(
                animation: controller,
                builder: (BuildContext context, Widget child) {
                  return new Text(
                    '${duration.inSeconds}',
                    style: new TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 50.0,
                    ),
                  );
                }),
            new Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                new RaisedButton(
                  padding: const EdgeInsets.all(15.0),
                  textColor: Colors.white,
                  color: Colors.redAccent,
                  onPressed: () {
                    setState(() {
                      controller.reverse(from: 1);
                    });
                  },
                  child: new Text("Start"),
                ),
                new RaisedButton(
                  padding: const EdgeInsets.all(15.0),
                  textColor: Colors.white,
                  color: Colors.redAccent,
                  onPressed: () {
                    setState(() {
                      controller.reset();
                    });
                  },
                  child: new Text("Reset"),
                ),
              ],
            ),
          ],
        ),
      ), 
    );
  }
}

你可以检查这个链接


推荐阅读