在pubspec.yaml文件中升级android_alarm_manager_plus的版本号至2.0.4或以上,并执行flutter packages get命令更新依赖。以下是更新后的代码示例:
pubspec.yaml文件:
dependencies: flutter: sdk: flutter android_alarm_manager_plus: ^2.0.4
实现定时任务的dart文件:
import 'dart:async'; import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart'; import 'package:flutter/material.dart';
class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); }
class _MyAppState extends State
Future
Future
@override void initState() { super.initState();
// 每秒更新一次_counter的值
AndroidAlarmManager.periodic(Duration(seconds: 1), 0, _incrementCounterPeriodically);
}
@override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('定时任务示例'), ), body: Center( child: Text('计数器: $_counter'), ), ), ); } }