Flutter如何实现本地通知系统的记账提醒功能

在Flutter中,我想实现一个本地通知系统的记账提醒功能。具体需求是:用户可以设置每天固定时间接收提醒,通知内容包含当日待记账的金额或事项。目前尝试了flutter_local_notifications插件,但遇到两个问题:1. 如何让通知在应用关闭时依然能准时触发?2. 如何动态更新通知内容(比如根据用户设置的记账金额变化)?是否需要结合后台任务或其他插件来实现?希望有经验的朋友能分享具体实现方案或代码示例。

2 回复

使用Flutter实现本地通知系统的记账提醒功能,需借助flutter_local_notifications插件。步骤如下:

  1. 添加插件依赖到pubspec.yaml。
  2. 配置Android和iOS的通知权限。
  3. 初始化通知插件并请求权限。
  4. 使用插件设置定时或周期性通知,如每日提醒记账。
  5. 处理用户点击通知后的逻辑。

示例代码:

await flutterLocalNotificationsPlugin.periodicallyShow(
  0, '记账提醒', '记得记录今天的开销哦!', RepeatInterval.daily,
);

更多关于Flutter如何实现本地通知系统的记账提醒功能的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中实现本地通知系统的记账提醒功能,可以使用flutter_local_notifications插件。以下是实现步骤和核心代码:

1. 添加依赖

pubspec.yaml中添加:

dependencies:
  flutter_local_notifications: ^16.3.0

2. 配置通知权限(Android & iOS)

Android配置:

  • AndroidManifest.xml添加权限:
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
  • 创建drawable资源文件夹存放通知图标

iOS配置:

  • Info.plist添加权限描述:
<key>NSRemindersUsageDescription</key>
<string>需要提醒权限来发送记账提醒</string>

3. 初始化通知插件

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

final FlutterLocalNotificationsPlugin notificationsPlugin =
    FlutterLocalNotificationsPlugin();

Future<void> initNotifications() async {
  // Android初始化配置
  const AndroidInitializationSettings androidSettings =
      AndroidInitializationSettings('@mipmap/ic_launcher');
  
  // iOS初始化配置
  final DarwinInitializationSettings iosSettings =
      DarwinInitializationSettings(
        requestAlertPermission: true,
        requestBadgePermission: true,
        requestSoundPermission: true,
      );

  final InitializationSettings settings = InitializationSettings(
    android: androidSettings,
    iOS: iosSettings,
  );

  await notificationsPlugin.initialize(settings);
}

4. 请求通知权限

Future<bool> requestPermissions() async {
  if (Platform.isIOS) {
    return await notificationsPlugin
        .resolvePlatformSpecificImplementation<
            DarwinFlutterLocalNotificationsPlugin>()
        ?.requestPermissions() ?? false;
  }
  return true;
}

5. 创建记账提醒方法

Future<void> scheduleAccountingReminder({
  required int id,
  required String title,
  required String body,
  required TimeOfDay time,
  required List<int> repeatDays, // 0-6 表示周日到周六
}) async {
  final timeNow = DateTime.now();
  final scheduledTime = DateTime(
    timeNow.year,
    timeNow.month,
    timeNow.day,
    time.hour,
    time.minute,
  );

  for (int day in repeatDays) {
    final difference = (day - timeNow.weekday + 7) % 7;
    final notificationTime = scheduledTime.add(Duration(days: difference));
    
    if (notificationTime.isAfter(timeNow)) {
      await notificationsPlugin.zonedSchedule(
        id + day, // 确保每个通知有唯一ID
        title,
        body,
        tz.TZDateTime.from(notificationTime, tz.local),
        const NotificationDetails(
          android: AndroidNotificationDetails(
            'accounting_channel',
            '记账提醒',
            channelDescription: '用于定时提醒记录日常开销',
            importance: Importance.high,
            priority: Priority.high,
          ),
          iOS: DarwinNotificationDetails(
            sound: 'default.wav',
            presentAlert: true,
            presentBadge: true,
            presentSound: true,
          ),
        ),
        uiLocalNotificationDateInterpretation:
            UILocalNotificationDateInterpretation.absoluteTime,
        matchDateTimeComponents: DateTimeComponents.dayOfWeekAndTime,
      );
    }
  }
}

6. 使用示例

// 设置每天下午6点的记账提醒
await scheduleAccountingReminder(
  id: 1,
  title: '记账提醒',
  body: '记得记录今天的开销哦!',
  time: TimeOfDay(hour: 18, minute: 0),
  repeatDays: [1, 2, 3, 4, 5, 6, 7], // 每天重复
);

7. 取消提醒

// 取消特定提醒
await notificationsPlugin.cancel(notificationId);

// 取消所有提醒
await notificationsPlugin.cancelAll();

注意事项:

  1. 需要处理时区问题,建议使用timezone
  2. 应用被杀掉后定时通知仍会触发
  3. 测试时注意设置合适的时间间隔
  4. iOS需要在真机上测试通知功能

这样就能实现一个完整的本地记账提醒系统,用户可以在指定时间收到记账提醒通知。

回到顶部