refactor(apps): 主题系统迁移至 ColorScheme + 扩展架构并支持 Dark Mode

This commit is contained in:
qzl
2026-03-27 19:07:39 +08:00
parent ecc1ec6ce4
commit ae29a8209b
146 changed files with 4301 additions and 3200 deletions
@@ -1,31 +0,0 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../domain/models/reminder_payload.dart';
class IOSNotificationPayloadBridge {
static const String _key = 'pending_notification_payload';
final SharedPreferences _prefs;
IOSNotificationPayloadBridge(this._prefs);
Future<ReminderPayload?> getPendingPayload() async {
final raw = _prefs.getString(_key);
if (raw == null || raw.isEmpty) {
return null;
}
try {
final json = Map<String, dynamic>.from(jsonDecode(raw) as Map);
return ReminderPayload.fromJson(json);
} catch (_) {
return null;
}
}
Future<void> setPendingPayload(ReminderPayload payload) async {
await _prefs.setString(_key, jsonEncode(payload.toJson()));
}
Future<void> clearPendingPayload() async {
await _prefs.remove(_key);
}
}
@@ -1,308 +0,0 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest.dart' as tz_data;
import 'package:timezone/timezone.dart' as tz;
import '../../../../core/l10n/l10n.dart';
import 'reminder_notification_callbacks.dart';
import '../../../calendar/data/models/schedule_item_model.dart';
import '../../domain/models/reminder_payload.dart';
class LocalNotificationService {
final FlutterLocalNotificationsPlugin _plugin;
bool _initialized = false;
LocalNotificationService({FlutterLocalNotificationsPlugin? plugin})
: _plugin = plugin ?? FlutterLocalNotificationsPlugin();
Future<void> initialize() async {
if (_initialized) {
return;
}
tz_data.initializeTimeZones();
const android = AndroidInitializationSettings('@mipmap/ic_launcher');
const ios = DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
);
final settings = InitializationSettings(android: android, iOS: ios);
await _plugin.initialize(
settings,
onDidReceiveNotificationResponse:
ReminderNotificationCallbacks.onForegroundResponse,
onDidReceiveBackgroundNotificationResponse:
reminderNotificationTapBackground,
);
final androidImpl = _plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
await androidImpl?.requestNotificationsPermission();
await androidImpl?.requestExactAlarmsPermission();
await androidImpl?.requestFullScreenIntentPermission();
final iosImpl = _plugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>();
await iosImpl?.requestPermissions(alert: true, badge: true, sound: true);
_initialized = true;
}
Future<void> upsertEventReminder(ScheduleItemModel event) async {
await initialize();
if (event.status != ScheduleStatus.active ||
event.metadata?.reminderMinutes == null) {
await cancelEventReminder(event.id);
return;
}
final now = DateTime.now();
final reminderMinutes = event.metadata?.reminderMinutes ?? 0;
final fireAt = event.startAt.subtract(Duration(minutes: reminderMinutes));
if (fireAt.isBefore(now)) {
await cancelEventReminder(event.id);
return;
}
await cancelEventReminder(event.id);
await _scheduleRemindersFrom(event: event, firstFireAt: fireAt);
}
Future<void> scheduleReminderAt(
ScheduleItemModel event,
DateTime fireAt,
) async {
await initialize();
await cancelEventReminder(event.id);
await _scheduleRemindersFrom(event: event, firstFireAt: fireAt);
}
Future<void> cancelEventReminder(String eventId) async {
await initialize();
final pending = await _plugin.pendingNotificationRequests();
for (final request in pending) {
final payload = _decodePayload(request.payload);
if (payload == null) {
continue;
}
if (payload.eventId == eventId ||
payload.aggregateIds.contains(eventId)) {
await _plugin.cancel(request.id);
}
}
await _plugin.cancel(_notificationIdForEvent(eventId));
}
Future<void> rebuildUpcomingReminders(
Iterable<ScheduleItemModel> events,
) async {
await initialize();
for (final event in events) {
await upsertEventReminder(event);
}
}
int _notificationIdForEvent(String eventId) {
return eventId.hashCode & 0x7fffffff;
}
int _notificationIdForEventCycle(
String eventId,
DateTime fireAt,
ReminderPayloadMode mode,
) {
final cycleMinute =
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds;
return '$eventId|$cycleMinute|${mode.value}'.hashCode & 0x7fffffff;
}
Future<AndroidScheduleMode> _resolveAndroidScheduleMode() async {
final androidImpl = _plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
if (androidImpl == null) {
return AndroidScheduleMode.exactAllowWhileIdle;
}
final canScheduleExact =
await androidImpl.canScheduleExactNotifications() ?? false;
return canScheduleExact
? AndroidScheduleMode.exactAllowWhileIdle
: AndroidScheduleMode.inexactAllowWhileIdle;
}
NotificationDetails _buildNotificationDetails(DateTime fireAt) {
return NotificationDetails(
android: AndroidNotificationDetails(
'calendar_alarm_channel_v2',
L10n.current.notificationChannelName,
channelDescription: L10n.current.notificationChannelDescription,
importance: Importance.max,
priority: Priority.max,
category: AndroidNotificationCategory.alarm,
audioAttributesUsage: AudioAttributesUsage.alarm,
fullScreenIntent: true,
playSound: true,
enableVibration: true,
vibrationPattern: Int64List.fromList([0, 1000, 500, 1200]),
timeoutAfter: 30000,
autoCancel: true,
groupKey: _getGroupKey(fireAt),
),
iOS: DarwinNotificationDetails(
presentAlert: true,
presentSound: true,
presentBadge: true,
threadIdentifier: _getThreadIdentifier(fireAt),
),
);
}
String _getThreadIdentifier(DateTime fireAt) {
final bucket =
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds;
return 'calendar_reminder_$bucket';
}
String _getGroupKey(DateTime fireAt) {
final bucket =
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds;
return 'com.socialapp.calendar.$bucket';
}
Future<void> _scheduleSingleReminder({
required ScheduleItemModel event,
required DateTime fireAt,
}) async {
final notificationId = _notificationIdForEventCycle(
event.id,
fireAt,
ReminderPayloadMode.single,
);
final payload = ReminderPayload(
eventId: event.id,
title: event.title,
startAt: event.startAt,
endAt: event.endAt,
timezone: event.timezone,
location: event.metadata?.location,
notes: event.metadata?.notes,
color: event.metadata?.color,
mode: ReminderPayloadMode.single,
fireTimeBucket:
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds,
version: 1,
);
final details = _buildNotificationDetails(fireAt);
final scheduledAt = tz.TZDateTime.from(fireAt, tz.local);
final mode = await _resolveAndroidScheduleMode();
try {
await _plugin.zonedSchedule(
notificationId,
event.title,
_buildReminderBody(event, event.metadata?.reminderMinutes ?? 0),
scheduledAt,
details,
payload: jsonEncode(payload.toJson()),
androidScheduleMode: mode,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
} catch (_) {
await _plugin.zonedSchedule(
notificationId,
event.title,
_buildReminderBody(event, event.metadata?.reminderMinutes ?? 0),
scheduledAt,
details,
payload: jsonEncode(payload.toJson()),
androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
}
Future<void> _scheduleRemindersFrom({
required ScheduleItemModel event,
required DateTime firstFireAt,
}) async {
final endAt = event.endAt;
var cursor = firstFireAt;
if (endAt == null) {
await _scheduleSingleReminder(event: event, fireAt: cursor);
return;
}
while (cursor.isBefore(endAt)) {
await _scheduleSingleReminder(event: event, fireAt: cursor);
cursor = cursor.add(const Duration(minutes: 10));
}
}
ReminderPayload? _decodePayload(String? raw) {
if (raw == null || raw.isEmpty) {
return null;
}
try {
final json = Map<String, dynamic>.from(jsonDecode(raw) as Map);
return ReminderPayload.fromJson(json);
} catch (_) {
return null;
}
}
String _buildReminderBody(ScheduleItemModel event, int reminderMinutes) {
final when = reminderMinutes == 0
? L10n.current.notificationStartsNow
: L10n.current.notificationStartsInMinutes(reminderMinutes);
final location = event.metadata?.location;
final notes = event.metadata?.notes;
final buffer = StringBuffer(when);
if (location != null && location.isNotEmpty) {
buffer.write('\n${L10n.current.notificationLocation(location)}');
}
if (notes != null && notes.isNotEmpty) {
final preview = notes.length > 30
? '${notes.substring(0, 30)}...'
: notes;
buffer.write('\n${L10n.current.notificationNotes(preview)}');
}
return buffer.toString();
}
Future<void> handleNotificationResponse(NotificationResponse response) async {
final payloadRaw = response.payload;
if (payloadRaw == null || payloadRaw.isEmpty) {
return;
}
ReminderPayload payload;
try {
payload = ReminderPayload.fromJson(
Map<String, dynamic>.from(jsonDecode(payloadRaw) as Map),
);
} catch (_) {
debugPrint('failed to handle reminder notification response');
return;
}
ReminderNotificationCallbacks.onNotificationPayloadReceived?.call(payload);
}
}
@@ -1,152 +0,0 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../domain/models/reminder_payload.dart';
typedef ReminderNotificationResponseHandler =
Future<void> Function(NotificationResponse response);
class ReminderNotificationCallbacks {
static const String _pendingKey =
'calendar_reminder_pending_notification_responses_v1';
static ReminderNotificationResponseHandler? _responseHandler;
static Future<void> _pendingStorageLock = Future<void>.value();
static void Function(ReminderPayload)? onNotificationPayloadReceived;
@visibleForTesting
static Future<void> resetForTest() async {
_responseHandler = null;
_pendingStorageLock = Future<void>.value();
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_pendingKey);
}
static Future<void> bindResponseHandler(
ReminderNotificationResponseHandler handler,
) async {
_responseHandler = handler;
await _drainPendingResponses();
}
static Future<void> onForegroundResponse(
NotificationResponse response,
) async {
final handler = _responseHandler;
if (handler == null) {
await _enqueuePendingResponse(response);
return;
}
try {
await handler(response);
} catch (_) {
await _enqueuePendingResponse(response);
}
}
static Future<void> onBackgroundResponse(
NotificationResponse response,
) async {
final handler = _responseHandler;
if (handler == null) {
await _enqueuePendingResponse(response);
return;
}
try {
await handler(response);
} catch (_) {
await _enqueuePendingResponse(response);
}
}
static Future<T> _withPendingStorageLock<T>(Future<T> Function() operation) {
final completer = Completer<void>();
final waitForTurn = _pendingStorageLock;
_pendingStorageLock = waitForTurn.then((_) => completer.future);
return waitForTurn.then((_) => operation()).whenComplete(() {
if (!completer.isCompleted) {
completer.complete();
}
});
}
static Future<void> _enqueuePendingResponse(
NotificationResponse response,
) async {
await _withPendingStorageLock(() async {
final prefs = await SharedPreferences.getInstance();
final current = prefs.getStringList(_pendingKey) ?? const <String>[];
final encoded = jsonEncode({
'id': response.id,
'actionId': response.actionId,
'payload': response.payload,
'type': response.notificationResponseType.index,
'input': response.input,
});
await prefs.setStringList(_pendingKey, <String>[...current, encoded]);
});
}
static Future<void> _drainPendingResponses() async {
final handler = _responseHandler;
if (handler == null) {
return;
}
await _withPendingStorageLock(() async {
final prefs = await SharedPreferences.getInstance();
final pending = prefs.getStringList(_pendingKey) ?? const <String>[];
if (pending.isEmpty) {
return;
}
final remaining = <String>[];
for (final raw in pending) {
Map<String, dynamic> parsed;
try {
parsed = Map<String, dynamic>.from(jsonDecode(raw) as Map);
} catch (_) {
continue;
}
final id = parsed['id'] as int?;
final actionId = parsed['actionId'] as String?;
final payload = parsed['payload'] as String?;
final typeIndex = (parsed['type'] as int?) ?? 0;
final input = parsed['input'] as String?;
final type = NotificationResponseType.values[typeIndex.clamp(0, 1)];
try {
await handler(
NotificationResponse(
id: id,
actionId: actionId,
payload: payload,
input: input,
notificationResponseType: type,
),
);
} catch (_) {
remaining.add(raw);
}
}
if (remaining.isEmpty) {
await prefs.remove(_pendingKey);
return;
}
await prefs.setStringList(_pendingKey, remaining);
});
}
}
@pragma('vm:entry-point')
Future<void> reminderNotificationTapBackground(
NotificationResponse response,
) async {
await ReminderNotificationCallbacks.onBackgroundResponse(response);
}
@@ -1,182 +0,0 @@
class ReminderPayload {
final String eventId;
final String title;
final DateTime startAt;
final DateTime? endAt;
final String timezone;
final String? location;
final String? notes;
final String? color;
final ReminderPayloadMode mode;
final List<String> aggregateIds;
final int? fireTimeBucket;
final int version;
const ReminderPayload({
required this.eventId,
required this.title,
required this.startAt,
required this.timezone,
this.endAt,
this.location,
this.notes,
this.color,
this.mode = ReminderPayloadMode.single,
this.aggregateIds = const [],
this.fireTimeBucket,
this.version = 1,
});
ReminderPayload copyWith({
String? eventId,
String? title,
DateTime? startAt,
DateTime? endAt,
String? timezone,
String? location,
String? notes,
String? color,
ReminderPayloadMode? mode,
List<String>? aggregateIds,
int? fireTimeBucket,
int? version,
}) {
return ReminderPayload(
eventId: eventId ?? this.eventId,
title: title ?? this.title,
startAt: startAt ?? this.startAt,
endAt: endAt ?? this.endAt,
timezone: timezone ?? this.timezone,
location: location ?? this.location,
notes: notes ?? this.notes,
color: color ?? this.color,
mode: mode ?? this.mode,
aggregateIds: aggregateIds ?? this.aggregateIds,
fireTimeBucket: fireTimeBucket ?? this.fireTimeBucket,
version: version ?? this.version,
);
}
Map<String, dynamic> toJson() {
return {
'eventId': eventId,
'title': title,
'startAt': startAt.toIso8601String(),
'endAt': endAt?.toIso8601String(),
'timezone': timezone,
'location': location,
'notes': notes,
'color': color,
'mode': mode.value,
'aggregateIds': aggregateIds,
'fireTimeBucket': fireTimeBucket,
'version': version,
};
}
factory ReminderPayload.fromJson(Map<String, dynamic> json) {
final eventId = (json['eventId'] as String?) ?? '';
if (eventId.isEmpty) {
throw const FormatException('eventId is required');
}
final startAtRaw = json['startAt'] as String?;
if (startAtRaw == null || startAtRaw.isEmpty) {
throw const FormatException('startAt is required');
}
final parsedStartAt = DateTime.parse(startAtRaw);
final mode = ReminderPayloadMode.fromValue(
(json['mode'] as String?) ?? 'single',
);
final aggregateIds = (json['aggregateIds'] as List<dynamic>? ?? const [])
.map((item) => item.toString())
.toList();
if (mode == ReminderPayloadMode.aggregate && aggregateIds.length < 2) {
throw const FormatException('aggregateIds must contain at least 2 items');
}
return ReminderPayload(
eventId: eventId,
title: (json['title'] as String?) ?? '',
startAt: parsedStartAt,
endAt: json['endAt'] != null
? DateTime.parse(json['endAt'] as String)
: null,
timezone: (json['timezone'] as String?) ?? 'UTC',
location: json['location'] as String?,
notes: json['notes'] as String?,
color: json['color'] as String?,
mode: mode,
aggregateIds: aggregateIds,
fireTimeBucket: json['fireTimeBucket'] as int?,
version: (json['version'] as int?) ?? 1,
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is ReminderPayload &&
other.eventId == eventId &&
other.title == title &&
other.startAt == startAt &&
other.endAt == endAt &&
other.timezone == timezone &&
other.location == location &&
other.notes == notes &&
other.color == color &&
other.mode == mode &&
_listEquals(other.aggregateIds, aggregateIds) &&
other.fireTimeBucket == fireTimeBucket &&
other.version == version;
}
@override
int get hashCode {
return Object.hash(
eventId,
title,
startAt,
endAt,
timezone,
location,
notes,
color,
mode,
Object.hashAll(aggregateIds),
fireTimeBucket,
version,
);
}
}
enum ReminderPayloadMode {
single('single'),
aggregate('aggregate');
const ReminderPayloadMode(this.value);
final String value;
static ReminderPayloadMode fromValue(String raw) {
return ReminderPayloadMode.values.firstWhere(
(item) => item.value == raw,
orElse: () => ReminderPayloadMode.single,
);
}
}
bool _listEquals(List<String> left, List<String> right) {
if (left.length != right.length) {
return false;
}
for (var i = 0; i < left.length; i++) {
if (left[i] != right[i]) {
return false;
}
}
return true;
}
@@ -1,7 +1,8 @@
import '../../../calendar/data/services/calendar_service.dart';
import '../../data/services/local_notification_service.dart';
import '../../../../data/services/calendar_service.dart';
import '../../../../data/models/reminder_payload.dart';
import '../../../../data/repositories/models/schedule_item_model.dart';
import '../../../../data/services/local_notification_service.dart';
import '../models/reminder_action.dart';
import '../models/reminder_payload.dart';
class ReminderActionExecutor {
final CalendarService _calendarService;
@@ -39,8 +40,11 @@ class ReminderActionExecutor {
}
Future<void> _snoozeEvent(String eventId) async {
final event = await _calendarService.getEventById(eventId);
if (event == null) {
late final ScheduleItemModel event;
try {
event = await _calendarService.getEventById(eventId);
} catch (_) {
await _notificationService.cancelEventReminder(eventId);
return;
}
final now = DateTime.now();
@@ -62,6 +66,10 @@ class ReminderActionExecutor {
}
Future<void> _archiveEvent(String eventId) async {
await _calendarService.archiveEvent(eventId);
try {
await _calendarService.archiveEvent(eventId);
} catch (_) {
await _notificationService.cancelEventReminder(eventId);
}
}
}
@@ -1,4 +1,4 @@
import '../models/reminder_payload.dart';
import '../../../../data/models/reminder_payload.dart';
class ReminderQueueManager {
ReminderPayload? _currentPayload;
@@ -2,9 +2,9 @@ import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../../../../core/l10n/l10n.dart';
import '../../../../core/theme/design_tokens.dart';
import '../../../../data/models/reminder_payload.dart';
import '../../../../shared/widgets/app_button.dart';
import '../../domain/services/reminder_queue_manager.dart';
import '../../domain/models/reminder_payload.dart';
class ReminderOverlay extends StatefulWidget {
const ReminderOverlay({
@@ -53,36 +53,41 @@ class _ReminderOverlayState extends State<ReminderOverlay> {
left: button.dx,
top: button.dy + box.size.height + 4,
width: 120,
child: Material(
elevation: 4,
borderRadius: BorderRadius.circular(8),
child: Container(
decoration: BoxDecoration(
color: AppColors.white,
child: Builder(
builder: (context) {
final colorScheme = Theme.of(context).colorScheme;
return Material(
elevation: 4,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: AppColors.borderSecondary),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_SnoozeOption(
label: context.l10n.notificationSnoozeMinutes(5),
onTap: () {
_hideSnoozeOptions();
_handleSnooze(5);
},
child: Container(
decoration: BoxDecoration(
color: colorScheme.surface,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: colorScheme.outlineVariant),
),
const Divider(height: 1, color: AppColors.borderSecondary),
_SnoozeOption(
label: context.l10n.notificationSnoozeMinutes(15),
onTap: () {
_hideSnoozeOptions();
_handleSnooze(15);
},
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_SnoozeOption(
label: context.l10n.notificationSnoozeMinutes(5),
onTap: () {
_hideSnoozeOptions();
_handleSnooze(5);
},
),
Divider(height: 1, color: colorScheme.outlineVariant),
_SnoozeOption(
label: context.l10n.notificationSnoozeMinutes(15),
onTap: () {
_hideSnoozeOptions();
_handleSnooze(15);
},
),
],
),
],
),
),
),
);
},
),
),
);
@@ -104,13 +109,14 @@ class _ReminderOverlayState extends State<ReminderOverlay> {
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final payload = _currentPayload;
if (payload == null) {
return const SizedBox.shrink();
}
return Container(
color: AppColors.white,
color: colorScheme.surface,
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(AppSpacing.lg),
@@ -121,7 +127,7 @@ class _ReminderOverlayState extends State<ReminderOverlay> {
Text(
payload.title,
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
color: AppColors.slate900,
color: colorScheme.onSurface,
fontWeight: FontWeight.w600,
),
textAlign: TextAlign.center,
@@ -129,9 +135,9 @@ class _ReminderOverlayState extends State<ReminderOverlay> {
const SizedBox(height: AppSpacing.sm),
Text(
DateFormat('HH:mm').format(DateTime.now()),
style: Theme.of(
context,
).textTheme.titleLarge?.copyWith(color: AppColors.slate500),
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: colorScheme.onSurfaceVariant,
),
textAlign: TextAlign.center,
),
const SizedBox(height: AppSpacing.xl),
@@ -169,6 +175,7 @@ class _SnoozeOption extends StatelessWidget {
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return InkWell(
onTap: onTap,
child: Padding(
@@ -180,7 +187,7 @@ class _SnoozeOption extends StatelessWidget {
label,
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: AppColors.slate900),
).textTheme.bodyMedium?.copyWith(color: colorScheme.onSurface),
),
),
);