You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用flutter_local_notifications为通知添加动态倒计时值?

用flutter_local_notifications实现动态倒计时通知

你当前的代码只在初始化时显示了一次通知,没有在倒计时变化时更新内容,所以看不到动态倒数的效果。要实现动态更新,核心是在倒计时的回调中,用同一个通知ID重复调用show方法覆盖原有通知,以此实现内容的动态变化。

完整实现示例

1. 依赖配置

先在pubspec.yaml中添加所需依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_local_notifications: ^16.1.0
  quiver: ^3.2.1

2. 实现代码

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('倒计时通知示例')),
        body: Center(
          child: ElevatedButton(
            onPressed: () => CountdownNotification().startCountdown(),
            child: const Text('开始60秒倒计时'),
          ),
        ),
      ),
    );
  }
}

class CountdownNotification {
  final FlutterLocalNotificationsPlugin _localNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
  static const int _notificationId = 1;

  CountdownNotification() {
    _initializeNotifications();
  }

  // 初始化通知插件并请求权限
  Future<void> _initializeNotifications() async {
    const AndroidInitializationSettings androidInit =
        AndroidInitializationSettings('@mipmap/ic_launcher');
    const IOSInitializationSettings iosInit = IOSInitializationSettings();
    const InitializationSettings initSettings =
        InitializationSettings(android: androidInit, iOS: iosInit);

    await _localNotificationsPlugin.initialize(initSettings);
    
    // Android 13+ 需要主动请求通知权限
    if (_localNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>() != null) {
      await _localNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()!
          .requestNotificationsPermission();
    }
  }

  Future<void> startCountdown() async {
    // 配置通知基础参数
    const AndroidNotificationDetails androidDetail = AndroidNotificationDetails(
      'timer_channel',
      '倒计时通知',
      channelDescription: '显示动态倒计时的通知渠道',
      importance: Importance.low,
      priority: Priority.low,
      ongoing: true, // 常驻通知,无法手动清除(倒计时中)
    );
    const IOSNotificationDetails iosDetail = IOSNotificationDetails();
    const NotificationDetails notificationDetail = NotificationDetails(
      android: androidDetail,
      iOS: iosDetail,
    );

    // 启动60秒倒计时,每秒触发一次更新
    CountdownTimer countdown =
        CountdownTimer(const Duration(seconds: 60), const Duration(seconds: 1));
    
    countdown.listen((event) {
      int remainingSeconds = event.remaining.inSeconds;
      // 用同一ID更新通知内容
      _localNotificationsPlugin.show(
        _notificationId,
        '倒计时中',
        '剩余${remainingSeconds.toString().padLeft(2, '0')}秒',
        notificationDetail,
      );
    }).onDone(() {
      // 倒计时结束后,更新通知状态或直接取消
      _localNotificationsPlugin.show(
        _notificationId,
        '倒计时结束',
        '60秒倒计时已完成',
        notificationDetail.copyWith(
          android: const AndroidNotificationDetails(
            'timer_channel',
            '倒计时通知',
            channelDescription: '显示动态倒计时的通知渠道',
            importance: Importance.defaultImportance,
            priority: Priority.defaultPriority,
            ongoing: false, // 允许手动清除
          ),
        ),
      );
      // 也可以直接取消通知:_localNotificationsPlugin.cancel(_notificationId);
    });
  }
}

关键说明

  • 同一ID更新通知:使用相同的notificationId调用show方法时,会直接覆盖之前的通知,这是实现动态内容的核心。
  • 权限处理:Android 13及以上版本必须主动请求POST_NOTIFICATIONS权限,否则通知无法正常显示。
  • 常驻通知控制:设置ongoing: true可以让倒计时期间的通知无法被用户手动关闭,结束后建议改为false恢复正常交互。
  • 倒计时结束处理:根据需求,倒计时结束后可以更新通知内容提示完成,或者直接取消通知。

内容的提问来源于stack exchange,提问作者Kdon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 09:57:13