如何运行倒计时计时器时,应用程序是关闭在Flutter

63lcw9qa  于 2023-05-30  发布在  Flutter
关注(0)|答案(1)|浏览(294)

Flutter如何运行倒计时计时器时,应用程序被关闭,我试过,但计时器每次从初始阶段开始,当我从后台删除应用程序

31moq8wy

31moq8wy1#

后台运行倒计时,可以使用**android_alarm_manager**包。此软件包允许您计划即使在应用关闭时仍继续运行的任务。通过将这个包与您的倒计时计时器逻辑一起添加,您可以确保计时器在后台保持运行。
请相应地实现下面的代码

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

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

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

class CountdownScreen extends StatefulWidget {
  @override
  _CountdownScreenState createState() => _CountdownScreenState();
}

class _CountdownScreenState extends State<CountdownScreen> {
  int _duration = 60;
  Timer _timer;

  @override
  void initState() {
    super.initState();
    startCountdown();
  }

  void startCountdown() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_duration <= 0) {
        timer.cancel();
        // Timer finished
        print('Countdown complete!');
      } else {
        setState(() {
          // Update timer display or perform other actions
          print('Time remaining: $_duration seconds');
          _duration--;
        });
      }
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Countdown Timer'),
      ),
      body: Center(
        child: Text(
          'Time remaining: $_duration seconds',
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

我希望这对你有帮助。

相关问题