feat: 实现日历提醒 in-app fallback 机制及通知服务重构

This commit is contained in:
zl-q
2026-03-20 01:30:34 +08:00
parent 7fd536e976
commit d574128815
55 changed files with 4565 additions and 647 deletions
@@ -19,6 +19,9 @@
<receiver
android:exported="false"
android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
<receiver
android:exported="false"
android:name="com.dexterous.flutterlocalnotifications.ActionBroadcastReceiver" />
<receiver
android:exported="false"
android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
+4
View File
@@ -1,4 +1,5 @@
import Flutter
import flutter_local_notifications
import UIKit
import UserNotifications
@@ -8,6 +9,9 @@ import UserNotifications
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { registry in
GeneratedPluginRegistrant.register(with: registry)
}
GeneratedPluginRegistrant.register(with: self)
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
+9
View File
@@ -20,6 +20,7 @@ import '../../features/calendar/ui/calendar_state_manager.dart';
import '../../features/friends/data/friends_api.dart';
import '../../features/messages/data/inbox_api.dart';
import '../../features/settings/data/settings_api.dart';
import '../../features/settings/data/services/settings_user_cache.dart';
import '../../features/users/data/users_api.dart';
import '../../features/todo/data/todo_api.dart';
@@ -82,6 +83,8 @@ Future<void> configureDependencies() async {
final settingsApi = SettingsApi(apiClient);
sl.registerSingleton<SettingsApi>(settingsApi);
sl.registerSingleton<SettingsUserCache>(SettingsUserCache());
final inboxApi = InboxApi(apiClient);
sl.registerSingleton<InboxApi>(inboxApi);
@@ -93,6 +96,9 @@ Future<void> configureDependencies() async {
tokenStorage: tokenStorage,
onLogout: () async {
apiClient.resetInterceptor();
if (sl.isRegistered<SettingsUserCache>()) {
sl<SettingsUserCache>().invalidate();
}
},
);
sl.registerSingleton<AuthRepository>(authRepository);
@@ -110,6 +116,9 @@ Future<void> configureDependencies() async {
});
apiClient.setAuthFailureCallback(() async {
if (sl.isRegistered<SettingsUserCache>()) {
sl<SettingsUserCache>().invalidate();
}
authBloc.add(
const AuthSessionInvalidated(
source: AuthInvalidationSource.unauthorized401,
@@ -1,13 +1,18 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:timezone/data/latest.dart' as tz_data;
import 'package:timezone/timezone.dart' as tz;
import 'reminder_notification_callbacks.dart';
import '../../features/calendar/data/models/schedule_item_model.dart';
import '../../features/calendar/reminders/models/reminder_action.dart';
import '../../features/calendar/reminders/models/reminder_payload.dart';
import '../../features/calendar/reminders/reminder_action_dedupe_store.dart';
import '../../features/calendar/reminders/reminder_overlap_policy.dart';
typedef ReminderNotificationActionHandler =
@@ -16,26 +21,51 @@ typedef ReminderNotificationActionHandler =
required ReminderPayload payload,
});
typedef ReminderPermissionFallbackTracker =
void Function({
required String actionExecutionId,
required String permissionState,
required String appLifecycleState,
required String platform,
});
typedef ReminderInAppReminderHandler =
Future<void> Function(ReminderPayload payload);
class LocalNotificationService {
static const String _iosCategoryId = 'calendar_reminder_actions_v1';
static const String _iosCategoryId = 'calendar_reminder_v2';
static const String _actionCancel = 'cancel';
static const String _actionSnooze = 'snooze_10m';
static const String _actionSnooze = 'snooze10m';
final FlutterLocalNotificationsPlugin _plugin;
final ReminderOverlapPolicy _overlapPolicy;
final ReminderPermissionFallbackTracker? _permissionFallbackTracker;
ReminderActionDedupeStore? _dedupeStore;
bool _initialized = false;
bool _canDeliverSystemNotification = true;
ReminderNotificationActionHandler? _actionHandler;
ReminderInAppReminderHandler? _inAppReminderHandler;
final Map<String, List<Timer>> _inAppFallbackTimersByEventId =
<String, List<Timer>>{};
LocalNotificationService({
FlutterLocalNotificationsPlugin? plugin,
ReminderOverlapPolicy? overlapPolicy,
ReminderActionDedupeStore? dedupeStore,
ReminderPermissionFallbackTracker? permissionFallbackTracker,
}) : _plugin = plugin ?? FlutterLocalNotificationsPlugin(),
_overlapPolicy = overlapPolicy ?? const ReminderOverlapPolicy();
_overlapPolicy = overlapPolicy ?? const ReminderOverlapPolicy(),
_dedupeStore = dedupeStore,
_permissionFallbackTracker = permissionFallbackTracker;
void bindActionHandler(ReminderNotificationActionHandler handler) {
_actionHandler = handler;
}
void bindInAppReminderHandler(ReminderInAppReminderHandler handler) {
_inAppReminderHandler = handler;
}
Future<void> initialize() async {
if (_initialized) {
return;
@@ -67,14 +97,28 @@ class LocalNotificationService {
await _plugin.initialize(
settings,
onDidReceiveNotificationResponse: _onNotificationResponse,
onDidReceiveNotificationResponse:
ReminderNotificationCallbacks.onForegroundResponse,
onDidReceiveBackgroundNotificationResponse:
reminderNotificationTapBackground,
);
final androidImpl = _plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
await androidImpl?.requestNotificationsPermission();
final androidPermissionGranted = await androidImpl
?.requestNotificationsPermission();
if (defaultTargetPlatform == TargetPlatform.android &&
androidPermissionGranted == false) {
_canDeliverSystemNotification = false;
_permissionFallbackTracker?.call(
actionExecutionId: 'permission_check',
permissionState: 'denied',
appLifecycleState: 'unknown',
platform: 'android',
);
}
await androidImpl?.requestExactAlarmsPermission();
await androidImpl?.requestFullScreenIntentPermission();
@@ -84,11 +128,37 @@ class LocalNotificationService {
>();
await iosImpl?.requestPermissions(alert: true, badge: true, sound: true);
await _ensureDedupeStore();
_initialized = true;
}
Future<void> _ensureDedupeStore() async {
if (_dedupeStore != null) {
return;
}
final prefs = await SharedPreferences.getInstance();
_dedupeStore = ReminderActionDedupeStore(prefs);
}
Future<void> _refreshAndroidNotificationAvailability() async {
if (defaultTargetPlatform != TargetPlatform.android) {
return;
}
final androidImpl = _plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
final enabled = await androidImpl?.areNotificationsEnabled();
if (enabled == null) {
return;
}
_canDeliverSystemNotification = enabled;
}
Future<void> upsertEventReminder(ScheduleItemModel event) async {
await initialize();
await _refreshAndroidNotificationAvailability();
if (event.status != ScheduleStatus.active ||
event.metadata?.reminderMinutes == null) {
await cancelEventReminder(event.id);
@@ -102,6 +172,14 @@ class LocalNotificationService {
return;
}
if (!_canDeliverSystemNotification) {
await _scheduleInAppFallbackRemindersFrom(
event: event,
firstFireAt: fireAt,
);
return;
}
await cancelEventReminder(event.id);
await _scheduleRemindersFrom(event: event, firstFireAt: fireAt);
}
@@ -111,12 +189,22 @@ class LocalNotificationService {
DateTime fireAt,
) async {
await initialize();
await _refreshAndroidNotificationAvailability();
if (!_canDeliverSystemNotification) {
await _scheduleInAppFallbackRemindersFrom(
event: event,
firstFireAt: fireAt,
);
return;
}
await cancelEventReminder(event.id);
await _scheduleRemindersFrom(event: event, firstFireAt: fireAt);
}
Future<void> cancelEventReminder(String eventId) async {
await initialize();
_cancelInAppFallbackTimers(eventId);
final pending = await _plugin.pendingNotificationRequests();
for (final request in pending) {
final payload = _decodePayload(request.payload);
@@ -136,6 +224,23 @@ class LocalNotificationService {
Iterable<ScheduleItemModel> events,
) async {
await initialize();
await _refreshAndroidNotificationAvailability();
if (!_canDeliverSystemNotification) {
_clearAllInAppFallbackTimers();
final now = DateTime.now();
final groups = _overlapPolicy.groupByMinute(events, now: now);
for (final group in groups) {
if (group.isAggregate) {
await _scheduleInAppAggregateFallback(group.events, group.fireAt);
continue;
}
await _scheduleInAppFallbackRemindersFrom(
event: group.events.first,
firstFireAt: group.fireAt,
);
}
return;
}
final now = DateTime.now();
final groups = _overlapPolicy.groupByMinute(events, now: now);
@@ -236,6 +341,9 @@ class LocalNotificationService {
notes: event.metadata?.notes,
color: event.metadata?.color,
mode: ReminderPayloadMode.single,
fireTimeBucket:
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds,
version: 1,
);
@@ -270,6 +378,185 @@ class LocalNotificationService {
}
}
Future<void> _scheduleInAppAggregateFallback(
List<ScheduleItemModel> events,
DateTime fireAt,
) async {
if (events.isEmpty) {
return;
}
final aggregateIds = events.map((event) => event.id).toList();
for (final eventId in aggregateIds) {
_cancelInAppFallbackTimers(eventId);
}
final first = events.first;
final payload = ReminderPayload(
eventId: first.id,
title: '你有${events.length}个日程提醒',
startAt: first.startAt,
endAt: first.endAt,
timezone: first.timezone,
mode: ReminderPayloadMode.aggregate,
aggregateIds: aggregateIds,
fireTimeBucket:
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds,
version: 1,
);
await _scheduleInAppFallbackPayload(
eventId: first.id,
fireAt: fireAt,
payload: payload,
relatedEventIds: aggregateIds,
);
}
Future<void> _scheduleInAppFallbackRemindersFrom({
required ScheduleItemModel event,
required DateTime firstFireAt,
}) async {
_cancelInAppFallbackTimers(event.id);
final endAt = event.endAt;
var cursor = firstFireAt;
Future<void> scheduleAt(DateTime fireAt) async {
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,
);
await _scheduleInAppFallbackPayload(
eventId: event.id,
fireAt: fireAt,
payload: payload,
relatedEventIds: <String>[event.id],
);
}
if (endAt == null) {
await scheduleAt(cursor);
return;
}
while (cursor.isBefore(endAt)) {
await scheduleAt(cursor);
cursor = cursor.add(const Duration(minutes: 10));
}
}
Future<Timer?> _scheduleInAppFallbackPayload({
required String eventId,
required DateTime fireAt,
required ReminderPayload payload,
required List<String> relatedEventIds,
}) async {
final handler = _inAppReminderHandler;
final bucket =
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds;
final actionExecutionId = '$eventId|fallback|$bucket';
_trackFallback(
actionExecutionId: actionExecutionId,
permissionState: 'denied',
);
if (handler == null) {
return null;
}
final now = DateTime.now();
final delay = fireAt.isAfter(now) ? fireAt.difference(now) : Duration.zero;
late final Timer timer;
timer = Timer(delay, () {
final activeHandler = _inAppReminderHandler;
if (activeHandler == null) {
_unregisterInAppFallbackTimer(relatedEventIds, timer);
return;
}
activeHandler(payload);
_unregisterInAppFallbackTimer(relatedEventIds, timer);
});
_registerInAppFallbackTimer(relatedEventIds, timer);
return timer;
}
void _registerInAppFallbackTimer(List<String> eventIds, Timer timer) {
for (final eventId in eventIds) {
final timers = _inAppFallbackTimersByEventId.putIfAbsent(
eventId,
() => <Timer>[],
);
timers.add(timer);
}
}
void _unregisterInAppFallbackTimer(List<String> eventIds, Timer timer) {
for (final eventId in eventIds) {
final timers = _inAppFallbackTimersByEventId[eventId];
if (timers == null) {
continue;
}
timers.remove(timer);
if (timers.isEmpty) {
_inAppFallbackTimersByEventId.remove(eventId);
}
}
}
void _cancelInAppFallbackTimers(String eventId) {
final timers = _inAppFallbackTimersByEventId.remove(eventId);
if (timers == null) {
return;
}
for (final timer in timers.toSet()) {
for (final entry in _inAppFallbackTimersByEventId.entries) {
entry.value.remove(timer);
}
timer.cancel();
}
_inAppFallbackTimersByEventId.removeWhere((_, value) => value.isEmpty);
}
void _clearAllInAppFallbackTimers() {
final allTimers = <Timer>{};
for (final timers in _inAppFallbackTimersByEventId.values) {
allTimers.addAll(timers);
}
_inAppFallbackTimersByEventId.clear();
for (final timer in allTimers) {
timer.cancel();
}
}
void _trackFallback({
required String actionExecutionId,
required String permissionState,
}) {
final lifecycleState =
WidgetsBinding.instance.lifecycleState?.name ?? 'unknown';
_permissionFallbackTracker?.call(
actionExecutionId: actionExecutionId,
permissionState: permissionState,
appLifecycleState: lifecycleState,
platform: 'android',
);
}
Future<void> _scheduleRemindersFrom({
required ScheduleItemModel event,
required DateTime firstFireAt,
@@ -309,6 +596,9 @@ class LocalNotificationService {
timezone: first.timezone,
mode: ReminderPayloadMode.aggregate,
aggregateIds: aggregateIds,
fireTimeBucket:
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds,
version: 1,
);
@@ -364,31 +654,60 @@ class LocalNotificationService {
return buffer.toString();
}
Future<void> _onNotificationResponse(NotificationResponse response) async {
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;
}
final actionId = response.actionId;
ReminderAction? action;
if (actionId == _actionCancel) {
action = ReminderAction.archive;
} else if (actionId == _actionSnooze) {
action = ReminderAction.snooze10m;
}
if (action == null) {
if (response.notificationResponseType ==
NotificationResponseType.selectedNotification) {
final presenter = _inAppReminderHandler;
if (presenter != null) {
await presenter(payload);
}
}
return;
}
final handler = _actionHandler;
if (handler == null) {
return;
}
try {
final payload = ReminderPayload.fromJson(
Map<String, dynamic>.from(jsonDecode(payloadRaw) as Map),
);
final actionId = response.actionId;
if (actionId == _actionCancel) {
await handler(action: ReminderAction.cancel, payload: payload);
final dedupeStore = _dedupeStore;
if (dedupeStore != null) {
final notificationId = response.id?.toString() ?? payload.eventId;
final fireTimeBucket =
payload.fireTimeBucket ??
(payload.startAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds);
final actionExecutionId =
'$notificationId|${action.value}|$fireTimeBucket';
final isNew = await dedupeStore.markIfNew(actionExecutionId);
if (!isNew) {
return;
}
if (actionId == _actionSnooze) {
await handler(action: ReminderAction.snooze10m, payload: payload);
}
} catch (_) {
debugPrint('failed to handle reminder notification response');
return;
}
await handler(action: action, payload: payload);
}
}
@@ -0,0 +1,156 @@
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 '../../features/calendar/reminders/reminder_cold_start_queue.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 final ReminderColdStartQueue _coldStartQueue =
ReminderColdStartQueue();
@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) {
_coldStartQueue.enqueue(() async {
Map<String, dynamic> parsed;
try {
parsed = Map<String, dynamic>.from(jsonDecode(raw) as Map);
} catch (_) {
return;
}
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);
}
});
}
await _coldStartQueue.replay();
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);
}
-6
View File
@@ -24,7 +24,6 @@ import '../../features/todo/ui/screens/todo_edit_screen.dart';
import '../../features/settings/ui/screens/settings_screen.dart';
import '../../features/settings/ui/screens/features_screen.dart';
import '../../features/settings/ui/screens/memory_screen.dart';
import '../../features/settings/ui/screens/account_screen.dart';
import '../../features/settings/ui/screens/edit_profile_screen.dart';
final _protectedRoutes = [
@@ -38,7 +37,6 @@ final _protectedRoutes = [
AppRoutes.settingsMain,
AppRoutes.settingsFeatures,
AppRoutes.settingsMemory,
AppRoutes.settingsAccount,
AppRoutes.settingsEditProfile,
AppRoutes.messageInviteList,
];
@@ -174,10 +172,6 @@ GoRouter createAppRouter(AuthBloc authBloc) {
path: AppRoutes.settingsMemory,
builder: (context, state) => const MemoryScreen(),
),
GoRoute(
path: AppRoutes.settingsAccount,
builder: (context, state) => const AccountScreen(),
),
GoRoute(
path: AppRoutes.settingsEditProfile,
builder: (context, state) => const EditProfileScreen(),
-1
View File
@@ -27,6 +27,5 @@ class AppRoutes {
static const settingsMain = '/settings';
static const settingsFeatures = '/settings/features';
static const settingsMemory = '/settings/memory';
static const settingsAccount = '/settings/account';
static const settingsEditProfile = '/edit-profile';
}
@@ -175,6 +175,9 @@ class _LoginViewState extends State<LoginView> {
mainContent: LayoutBuilder(
builder: (context, constraints) {
final bottomInset = MediaQuery.of(context).viewInsets.bottom;
final minContentHeight = constraints.hasBoundedHeight
? constraints.maxHeight
: AppSpacing.none;
return SingleChildScrollView(
padding: EdgeInsets.fromLTRB(
AppSpacing.lg,
@@ -183,7 +186,7 @@ class _LoginViewState extends State<LoginView> {
bottomInset + AppSpacing.lg,
),
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: constraints.maxHeight),
constraints: BoxConstraints(minHeight: minContentHeight),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 320),
@@ -1,17 +1,23 @@
enum ReminderAction {
cancel('cancel'),
snooze10m('snooze_10m'),
timeout30s('timeout_30s'),
autoArchive('auto_archive');
archive('archive'),
snooze10m('snooze10m');
const ReminderAction(this.value);
final String value;
static ReminderAction fromValue(String raw) {
return ReminderAction.values.firstWhere(
(item) => item.value == raw,
orElse: () => ReminderAction.timeout30s,
);
switch (raw) {
case 'archive':
case 'cancel':
case 'auto_archive':
return ReminderAction.archive;
case 'snooze10m':
case 'snooze_10m':
case 'timeout_30s':
return ReminderAction.snooze10m;
default:
throw ArgumentError.value(raw, 'raw', 'Unsupported reminder action');
}
}
}
@@ -9,6 +9,7 @@ class ReminderPayload {
final String? color;
final ReminderPayloadMode mode;
final List<String> aggregateIds;
final int? fireTimeBucket;
final int version;
const ReminderPayload({
@@ -22,6 +23,7 @@ class ReminderPayload {
this.color,
this.mode = ReminderPayloadMode.single,
this.aggregateIds = const [],
this.fireTimeBucket,
this.version = 1,
});
@@ -36,6 +38,7 @@ class ReminderPayload {
String? color,
ReminderPayloadMode? mode,
List<String>? aggregateIds,
int? fireTimeBucket,
int? version,
}) {
return ReminderPayload(
@@ -49,6 +52,7 @@ class ReminderPayload {
color: color ?? this.color,
mode: mode ?? this.mode,
aggregateIds: aggregateIds ?? this.aggregateIds,
fireTimeBucket: fireTimeBucket ?? this.fireTimeBucket,
version: version ?? this.version,
);
}
@@ -65,6 +69,7 @@ class ReminderPayload {
'color': color,
'mode': mode.value,
'aggregateIds': aggregateIds,
'fireTimeBucket': fireTimeBucket,
'version': version,
};
}
@@ -104,6 +109,7 @@ class ReminderPayload {
color: json['color'] as String?,
mode: mode,
aggregateIds: aggregateIds,
fireTimeBucket: json['fireTimeBucket'] as int?,
version: (json['version'] as int?) ?? 1,
);
}
@@ -124,6 +130,7 @@ class ReminderPayload {
other.color == color &&
other.mode == mode &&
_listEquals(other.aggregateIds, aggregateIds) &&
other.fireTimeBucket == fireTimeBucket &&
other.version == version;
}
@@ -140,6 +147,7 @@ class ReminderPayload {
color,
mode,
Object.hashAll(aggregateIds),
fireTimeBucket,
version,
);
}
@@ -0,0 +1,52 @@
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
typedef SetStringListFn = Future<bool> Function(String key, List<String> value);
class ReminderActionDedupeStore {
static const String _key = 'calendar_reminder_action_dedupe_v1';
static const int _maxEntries = 512;
final SharedPreferences _prefs;
final SetStringListFn _setStringList;
Future<void> _queue = Future<void>.value();
ReminderActionDedupeStore(
SharedPreferences prefs, {
SetStringListFn? setStringList,
}) : _prefs = prefs,
_setStringList = setStringList ?? prefs.setStringList;
Future<bool> markIfNew(String actionExecutionId) async {
final completer = Completer<bool>();
_queue = _queue
.then((_) async {
completer.complete(await _markIfNewInternal(actionExecutionId));
})
.catchError((_) {
if (!completer.isCompleted) {
completer.complete(false);
}
});
return completer.future;
}
Future<bool> _markIfNewInternal(String actionExecutionId) async {
final current = List<String>.from(
_prefs.getStringList(_key) ?? const <String>[],
);
if (current.contains(actionExecutionId)) {
return false;
}
current.add(actionExecutionId);
if (current.length > _maxEntries) {
current.removeRange(0, current.length - _maxEntries);
}
final saved = await _setStringList(_key, current);
return saved;
}
}
@@ -27,19 +27,20 @@ class ReminderActionExecutor {
required ReminderPayload payload,
}) async {
final ids = payload.mode == ReminderPayloadMode.aggregate
? payload.aggregateIds
? (payload.aggregateIds.isNotEmpty
? payload.aggregateIds
: <String>[payload.eventId])
: <String>[payload.eventId];
if (action == ReminderAction.cancel) {
if (action == ReminderAction.archive) {
for (final id in ids) {
await _notificationService.cancelEventReminder(id);
await _archiveEvent(id, ReminderAction.cancel);
await _archiveEvent(id, ReminderAction.archive);
}
return;
}
if (action == ReminderAction.snooze10m ||
action == ReminderAction.timeout30s) {
if (action == ReminderAction.snooze10m) {
for (final id in ids) {
await _snoozeEvent(id);
}
@@ -50,7 +51,6 @@ class ReminderActionExecutor {
final pending = await _outboxStore.listPending();
for (final item in pending) {
if (item.targetStatus != 'archived') {
await _outboxStore.markDone(item.opId);
continue;
}
try {
@@ -71,14 +71,14 @@ class ReminderActionExecutor {
final endAt = event.endAt;
if (endAt != null && !now.isBefore(endAt)) {
await _notificationService.cancelEventReminder(eventId);
await _archiveEvent(eventId, ReminderAction.autoArchive);
await _archiveEvent(eventId, ReminderAction.archive);
return;
}
final nextAt = now.add(const Duration(minutes: 10));
if (endAt != null && !nextAt.isBefore(endAt)) {
await _notificationService.cancelEventReminder(eventId);
await _archiveEvent(eventId, ReminderAction.autoArchive);
await _archiveEvent(eventId, ReminderAction.archive);
return;
}
@@ -0,0 +1,57 @@
import 'dart:async';
import 'dart:collection';
typedef ReminderColdStartReplayTask = Future<void> Function();
typedef ReminderColdStartTaskErrorHandler =
void Function(Object error, StackTrace stackTrace);
class ReminderColdStartQueue {
final Queue<ReminderColdStartReplayTask> _tasks =
Queue<ReminderColdStartReplayTask>();
final ReminderColdStartTaskErrorHandler? _onTaskError;
Future<void>? _inFlightReplay;
ReminderColdStartQueue({ReminderColdStartTaskErrorHandler? onTaskError})
: _onTaskError = onTaskError;
void enqueue(ReminderColdStartReplayTask task) {
_tasks.add(task);
}
Future<void> replay() {
final inFlightReplay = _inFlightReplay;
if (inFlightReplay != null) {
return inFlightReplay;
}
final replayCompleter = Completer<void>();
final replayFuture = replayCompleter.future;
_inFlightReplay = replayFuture;
scheduleMicrotask(() async {
try {
await _replayInternal();
replayCompleter.complete();
} catch (error, stackTrace) {
replayCompleter.completeError(error, stackTrace);
} finally {
if (identical(_inFlightReplay, replayFuture)) {
_inFlightReplay = null;
}
}
});
return replayFuture;
}
Future<void> _replayInternal() async {
while (_tasks.isNotEmpty) {
final task = _tasks.removeFirst();
try {
await task();
} catch (error, stackTrace) {
_onTaskError?.call(error, stackTrace);
}
}
}
}
@@ -0,0 +1,73 @@
import 'package:flutter/material.dart';
import '../../../../core/theme/design_tokens.dart';
import '../models/reminder_action.dart';
import '../models/reminder_payload.dart';
import '../reminder_action_executor.dart';
import 'reminder_presentation_coordinator.dart';
import 'widgets/reminder_action_sheet.dart';
class ReminderForegroundPresenter {
final GlobalKey<NavigatorState> _navigatorKey;
final ReminderActionExecutor _executor;
final ReminderPresentationCoordinator _coordinator;
bool _isPresenting = false;
ReminderForegroundPresenter({
required GlobalKey<NavigatorState> navigatorKey,
required ReminderActionExecutor executor,
ReminderPresentationCoordinator? coordinator,
}) : _navigatorKey = navigatorKey,
_executor = executor,
_coordinator = coordinator ?? ReminderPresentationCoordinator();
Future<void> present(ReminderPayload payload) async {
final context = _navigatorKey.currentContext;
if (context == null) {
return;
}
final lifecycleState = WidgetsBinding.instance.lifecycleState;
final isAppActive = lifecycleState == AppLifecycleState.resumed;
final shouldPresent = _coordinator.shouldPresent(
eventId: payload.eventId,
isAppActive: isAppActive,
);
if (!shouldPresent || _isPresenting) {
return;
}
_isPresenting = true;
try {
final action = await showModalBottomSheet<ReminderAction>(
context: context,
useRootNavigator: true,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (sheetContext) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.all(AppSpacing.md),
child: ReminderActionSheet(
onSnooze: () {
Navigator.of(sheetContext).pop(ReminderAction.snooze10m);
},
onArchive: () {
Navigator.of(sheetContext).pop(ReminderAction.archive);
},
),
),
);
},
);
if (action == null) {
return;
}
await _executor.handleAction(action: action, payload: payload);
} finally {
_isPresenting = false;
}
}
}
@@ -0,0 +1,29 @@
typedef ReminderPresentationNow = DateTime Function();
class ReminderPresentationCoordinator {
final Duration _dedupeWindow;
final ReminderPresentationNow _now;
final Map<String, DateTime> _lastPresentedAtByEventId = <String, DateTime>{};
ReminderPresentationCoordinator({
Duration dedupeWindow = const Duration(seconds: 30),
ReminderPresentationNow? now,
}) : _dedupeWindow = dedupeWindow,
_now = now ?? DateTime.now;
bool shouldPresent({required String eventId, required bool isAppActive}) {
if (!isAppActive) {
return false;
}
final currentTime = _now();
final lastPresentedAt = _lastPresentedAtByEventId[eventId];
if (lastPresentedAt != null &&
currentTime.difference(lastPresentedAt) < _dedupeWindow) {
return false;
}
_lastPresentedAtByEventId[eventId] = currentTime;
return true;
}
}
@@ -0,0 +1,58 @@
import 'package:flutter/material.dart';
import '../../../../../core/theme/design_tokens.dart';
import '../../../../../shared/widgets/app_button.dart';
class ReminderActionSheet extends StatelessWidget {
const ReminderActionSheet({
super.key,
required this.onSnooze,
required this.onArchive,
});
final VoidCallback onSnooze;
final VoidCallback onArchive;
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(AppSpacing.lg),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(AppRadius.xl),
border: Border.all(color: AppColors.borderSecondary),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'提醒操作',
textAlign: TextAlign.center,
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(color: AppColors.slate900),
),
const SizedBox(height: AppSpacing.lg),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: AppButton(
text: '稍后提醒',
isOutlined: true,
onPressed: onSnooze,
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: AppButton(text: '归档', onPressed: onArchive),
),
],
),
],
),
);
}
}
@@ -9,11 +9,13 @@ import '../../../../shared/widgets/app_loading_indicator.dart';
import '../../../../shared/widgets/back_title_page_header.dart';
import '../../../../shared/widgets/detail_header_action_menu.dart';
import '../../../../shared/widgets/destructive_action_sheet.dart';
import '../../../../shared/widgets/toast/toast.dart';
import '../../../../shared/widgets/toast/toast_type.dart';
import '../../data/services/calendar_service.dart';
import '../../data/models/schedule_item_model.dart';
import '../utils/event_color_resolver.dart';
enum _CalendarHeaderAction { edit, delete, share }
enum _CalendarHeaderAction { edit, delete, share, archive }
class CalendarEventDetailScreen extends StatefulWidget {
final String eventId;
@@ -190,6 +192,17 @@ class _CalendarEventDetailScreenState extends State<CalendarEventDetailScreen> {
),
);
}
if (event.status != ScheduleStatus.archived && event.canEdit) {
final isExpired = _isEventExpired(event);
items.add(
DetailHeaderActionItem<_CalendarHeaderAction>(
value: _CalendarHeaderAction.archive,
label: '归档',
icon: LucideIcons.archive,
enabled: !isExpired,
),
);
}
return DetailHeaderActionMenu<_CalendarHeaderAction>(
items: items,
@@ -197,6 +210,14 @@ class _CalendarEventDetailScreenState extends State<CalendarEventDetailScreen> {
);
}
bool _isEventExpired(ScheduleItemModel event) {
final now = DateTime.now();
if (event.endAt != null) {
return event.endAt!.isBefore(now);
}
return event.startAt.isBefore(now);
}
void _handleHeaderAction(
_CalendarHeaderAction action,
ScheduleItemModel event,
@@ -213,6 +234,9 @@ class _CalendarEventDetailScreenState extends State<CalendarEventDetailScreen> {
case _CalendarHeaderAction.share:
context.push(AppRoutes.calendarEventShare(event.id));
return;
case _CalendarHeaderAction.archive:
_archiveEvent();
return;
}
}
@@ -460,6 +484,29 @@ class _CalendarEventDetailScreenState extends State<CalendarEventDetailScreen> {
context.pop();
}
Future<void> _archiveEvent() async {
final confirmed = await showDestructiveActionSheet(
context,
title: '归档日程',
message: '归档后此日程将标记为过期,确定要归档吗?',
confirmText: '确认归档',
);
if (!confirmed) {
return;
}
try {
await sl<CalendarService>().archiveEvent(widget.eventId);
await _loadEvent();
if (mounted) {
Toast.show(context, '已归档', type: ToastType.success);
}
} catch (e) {
if (mounted) {
Toast.show(context, '归档失败', type: ToastType.error);
}
}
}
String _formatRangeLabel(DateTime startAt, DateTime? endAt) {
final dateLabel =
'${startAt.month}${startAt.day}${_getWeekday(startAt.weekday)}';
@@ -4,6 +4,7 @@ import '../../../../core/di/injection.dart';
import '../../../../core/notifications/local_notification_service.dart';
import '../../../../core/theme/design_tokens.dart';
import '../../../../shared/widgets/app_loading_indicator.dart';
import '../../../../shared/widgets/app_selection_sheet.dart';
import '../../../../shared/widgets/app_sheet_input_field.dart';
import '../../../../shared/widgets/back_title_page_header.dart';
import '../../../../shared/widgets/toast/toast.dart';
@@ -107,12 +108,21 @@ class _CreateEventSheetState extends State<CreateEventSheet>
event.metadata?.reminderMinutes,
);
} else {
final now =
widget.initialDate ?? _roundToNearestMinute(DateTime.now(), 5);
_startDate = now;
_startTime = now;
_endDate = now;
_endTime = now.add(const Duration(hours: 1));
final now = DateTime.now();
final initial = widget.initialDate;
final rounded = _roundToNearestMinute(now, 5);
_startDate = initial != null
? DateTime(
initial.year,
initial.month,
initial.day,
rounded.hour,
rounded.minute,
)
: rounded;
_startTime = _startDate;
_endDate = _startDate;
_endTime = _startDate.add(const Duration(hours: 1));
}
}
@@ -139,15 +149,19 @@ class _CreateEventSheetState extends State<CreateEventSheet>
@override
Widget build(BuildContext context) {
if (widget.pageMode) {
return Container(
color: AppColors.background,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildPageHeader(),
_buildTabBar(),
Expanded(child: _buildTabContent()),
],
return GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => FocusScope.of(context).unfocus(),
child: Container(
color: AppColors.background,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildPageHeader(),
_buildTabBar(),
Expanded(child: _buildTabContent()),
],
),
),
);
}
@@ -331,12 +345,7 @@ class _CreateEventSheetState extends State<CreateEventSheet>
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildTextField(
'标题',
_titleController,
'请输入日程标题',
autofocus: !_isEditing,
),
_buildTextField('标题', _titleController, '请输入日程标题'),
const SizedBox(height: 20),
_buildDateTimePicker('开始', _startDate, _startTime, (date, time) {
setState(() {
@@ -580,7 +589,6 @@ class _CreateEventSheetState extends State<CreateEventSheet>
}
Widget _buildReminderPicker() {
final options = _buildReminderOptions();
String labelOf(int? value) {
if (value == null) {
return '无提醒';
@@ -603,37 +611,51 @@ class _CreateEventSheetState extends State<CreateEventSheet>
),
),
const SizedBox(height: 8),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(AppRadius.lg),
border: Border.all(color: AppColors.border),
),
child: DropdownButtonHideUnderline(
child: DropdownButton<int?>(
value: _reminderMinutes,
isExpanded: true,
InkWell(
onTap: () async {
final options = _buildReminderOptions();
final selected = await showAppSelectionSheet<int?>(
context,
title: '选择提醒时间',
items: options
.map(
(value) => DropdownMenuItem<int?>(
value: value,
child: Text(
labelOf(value),
style: const TextStyle(
fontSize: 14,
color: AppColors.slate700,
),
),
),
)
.map((v) => AppSelectionItem(value: v, label: labelOf(v)))
.toList(),
onChanged: (value) {
setState(() {
_reminderMinutes = value;
});
},
selectedValue: _reminderMinutes,
);
if (selected != null) {
setState(() {
_reminderMinutes = selected;
});
}
},
borderRadius: BorderRadius.circular(AppRadius.md),
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.slate50,
borderRadius: BorderRadius.circular(AppRadius.md),
border: Border.all(color: AppColors.borderSecondary),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Text(
labelOf(_reminderMinutes),
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w500,
color: AppColors.slate900,
),
),
),
const Icon(
LucideIcons.chevronRight,
size: 16,
color: AppColors.slate400,
),
],
),
),
),
@@ -54,7 +54,7 @@ class _DateTimePickerSheetState extends State<DateTimePickerSheet> {
if (_selectedYear == minDate.year &&
_selectedMonth == minDate.month &&
_selectedDay == minDate.day) {
return _allHours.where((h) => h > minDate.hour).toList();
return _allHours.where((h) => h >= minDate.hour).toList();
}
return _allHours;
}
@@ -73,7 +73,7 @@ class _DateTimePickerSheetState extends State<DateTimePickerSheet> {
_selectedMonth == minDate.month &&
_selectedDay == minDate.day &&
_selectedHour == minDate.hour) {
return _allMinutes.where((m) => m > minDate.minute).toList();
return _allMinutes.where((m) => m >= minDate.minute).toList();
}
return _allMinutes;
}
@@ -100,6 +100,12 @@ class _DateTimePickerSheetState extends State<DateTimePickerSheet> {
_hourController = FixedExtentScrollController(
initialItem: _filteredHours.indexOf(_selectedHour),
);
if (_filteredMinutes.isEmpty) {
_selectedMinute = 0;
} else if (!_filteredMinutes.contains(_selectedMinute)) {
_selectedMinute = _filteredMinutes.first;
}
_minuteController = FixedExtentScrollController(
initialItem: _filteredMinutes.indexOf(_selectedMinute),
);
@@ -0,0 +1,19 @@
import '../../../../core/theme/design_tokens.dart';
class HomeKeyboardInsetCalculator {
static double compute({
required double rawViewInsetBottom,
required double bottomViewPadding,
}) {
if (rawViewInsetBottom <= AppSpacing.xs) {
return 0;
}
final adjustedInset = rawViewInsetBottom - bottomViewPadding;
if (adjustedInset <= AppSpacing.xs) {
return 0;
}
return adjustedInset;
}
}
@@ -14,6 +14,7 @@ import '../../../chat/presentation/bloc/agent_stage.dart';
import '../../../chat/presentation/bloc/chat_bloc.dart';
import '../../../messages/data/inbox_api.dart';
import '../../data/voice_recorder.dart';
import '../controllers/home_keyboard_inset_calculator.dart';
import '../controllers/home_message_viewport_controller.dart';
import '../controllers/home_viewport_coordinator.dart';
import '../../../../shared/widgets/app_pull_refresh_feedback.dart';
@@ -100,7 +101,6 @@ class _HomeScreenState extends State<HomeScreen>
double? _historyViewportMaxExtent;
final GlobalKey<HomeInputHostState> _inputHostKey =
GlobalKey<HomeInputHostState>();
double _stableKeyboardInset = 0;
@override
void initState() {
@@ -541,16 +541,10 @@ class _HomeScreenState extends State<HomeScreen>
double _effectiveKeyboardInset(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
final rawInset = mediaQuery.viewInsets.bottom;
if (rawInset <= AppSpacing.xs) {
_stableKeyboardInset = 0;
return 0;
}
// Only update stable if new value is larger (never decrease on jitter down)
if (rawInset > _stableKeyboardInset) {
_stableKeyboardInset = rawInset;
}
return _stableKeyboardInset;
return HomeKeyboardInsetCalculator.compute(
rawViewInsetBottom: mediaQuery.viewInsets.bottom,
bottomViewPadding: mediaQuery.viewPadding.bottom,
);
}
void _dismissKeyboard() {
@@ -0,0 +1,49 @@
import '../../../users/data/models/user_response.dart';
class SettingsUserCache {
UserResponse? _cachedUser;
Future<UserResponse>? _inflight;
int _generation = 0;
UserResponse? get cachedUser => _cachedUser;
Future<UserResponse> getOrLoad(Future<UserResponse> Function() loader) {
final cached = _cachedUser;
if (cached != null) {
return Future<UserResponse>.value(cached);
}
final inflight = _inflight;
if (inflight != null) {
return inflight;
}
final generation = _generation;
late final Future<UserResponse> request;
request = loader()
.then((user) {
if (generation == _generation) {
_cachedUser = user;
}
return user;
})
.whenComplete(() {
if (identical(_inflight, request)) {
_inflight = null;
}
});
_inflight = request;
return request;
}
void set(UserResponse user) {
_cachedUser = user;
}
void invalidate() {
_generation += 1;
_cachedUser = null;
_inflight = null;
}
}
@@ -1,223 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/theme/design_tokens.dart';
import '../../../../shared/widgets/app_pressable.dart';
import '../../../../shared/widgets/toast/toast.dart';
import '../../../../shared/widgets/toast/toast_type.dart';
import '../../../auth/presentation/bloc/auth_bloc.dart';
import '../../../auth/presentation/bloc/auth_event.dart';
import '../../../auth/presentation/bloc/auth_state.dart';
import '../../../../shared/widgets/app_button.dart';
import '../widgets/account_section_card.dart';
import '../widgets/settings_page_scaffold.dart';
class AccountScreen extends StatelessWidget {
const AccountScreen({super.key});
static const double _menuItemHeight = AppSpacing.xl * 2 + AppSpacing.md;
static const double _menuItemHorizontalPadding = AppSpacing.md;
static const double _menuIconSize = 20;
static const double _menuChevronSize = 18;
@override
Widget build(BuildContext context) {
return SettingsPageScaffold(
title: '账户',
onBack: () => context.pop(),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [_buildListSurface(context)],
),
);
}
Widget _buildListSurface(BuildContext context) {
return AccountSectionCard(
backgroundColor: AppColors.white,
borderColor: AppColors.borderSecondary,
contentPadding: const EdgeInsets.symmetric(
horizontal: AppSpacing.md,
vertical: AppSpacing.sm,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildMenuItem(
icon: Icons.edit,
title: '编辑资料',
onTap: () => context.push('/edit-profile'),
),
_buildDivider(),
_buildMenuItem(
icon: Icons.logout,
title: '退出登录',
titleColor: AppColors.feedbackErrorText,
iconColor: AppColors.feedbackErrorIcon,
trailingColor: AppColors.feedbackErrorIcon,
onTap: () => _showLogoutSheet(context),
),
],
),
);
}
Widget _buildMenuItem({
required IconData icon,
required String title,
required VoidCallback onTap,
Color titleColor = AppColors.slate900,
Color iconColor = AppColors.slate500,
Color trailingColor = AppColors.slate400,
}) {
return AppPressable(
onTap: onTap,
borderRadius: BorderRadius.circular(AppRadius.md),
child: Container(
constraints: const BoxConstraints(minHeight: _menuItemHeight),
padding: const EdgeInsets.symmetric(
horizontal: _menuItemHorizontalPadding,
vertical: AppSpacing.sm,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
width: _menuIconSize,
child: Icon(icon, size: _menuIconSize, color: iconColor),
),
const SizedBox(width: AppSpacing.md),
Text(
title,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
color: titleColor,
),
),
],
),
Icon(
Icons.chevron_right,
size: _menuChevronSize,
color: trailingColor,
),
],
),
),
);
}
Widget _buildDivider() {
return Container(
height: 1,
margin: const EdgeInsets.only(
left: _menuItemHorizontalPadding + _menuIconSize + AppSpacing.md,
right: _menuItemHorizontalPadding,
),
color: AppColors.borderTertiary,
);
}
void _showLogoutSheet(BuildContext context) {
showModalBottomSheet<void>(
context: context,
backgroundColor: Colors.transparent,
isScrollControlled: true,
builder: (sheetContext) => SafeArea(
top: false,
child: Container(
margin: const EdgeInsets.fromLTRB(
AppSpacing.md,
AppSpacing.none,
AppSpacing.md,
AppSpacing.md,
),
padding: const EdgeInsets.all(AppSpacing.lg),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(AppRadius.xl),
border: Border.all(color: AppColors.borderSecondary),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'退出登录',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w700,
color: AppColors.slate900,
),
textAlign: TextAlign.center,
),
const SizedBox(height: AppSpacing.xs),
const Text(
'确定退出当前账户吗?',
style: TextStyle(fontSize: 14, color: AppColors.slate500),
textAlign: TextAlign.center,
),
const SizedBox(height: AppSpacing.lg),
SizedBox(
height: 52,
child: GestureDetector(
onTap: () async {
Navigator.of(sheetContext).pop();
final authBloc = context.read<AuthBloc>();
authBloc.add(AuthLoggedOut());
try {
await authBloc.stream
.firstWhere((state) => state is AuthUnauthenticated)
.timeout(const Duration(seconds: 5));
} catch (_) {
if (context.mounted) {
Toast.show(
context,
'退出失败,请稍后重试',
type: ToastType.error,
);
}
return;
}
if (context.mounted) {
context.go('/');
}
},
child: Container(
decoration: BoxDecoration(
color: AppColors.feedbackErrorIcon,
borderRadius: BorderRadius.circular(AppRadius.full),
),
alignment: Alignment.center,
child: const Text(
'确认退出',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w700,
color: AppColors.white,
),
),
),
),
),
const SizedBox(height: AppSpacing.sm),
SizedBox(
height: 52,
child: AppButton(
text: '取消',
isOutlined: true,
onPressed: () => Navigator.of(sheetContext).pop(),
),
),
],
),
),
),
);
}
}
@@ -6,6 +6,7 @@ import '../../../../shared/widgets/app_button.dart';
import '../../../../shared/widgets/app_loading_indicator.dart';
import '../../../../shared/widgets/toast/toast.dart';
import '../../../../shared/widgets/toast/toast_type.dart';
import '../../data/services/settings_user_cache.dart';
import '../../../users/data/models/user_response.dart';
import '../../../users/data/users_api.dart';
import '../widgets/account_section_card.dart';
@@ -22,6 +23,7 @@ class _EditProfileScreenState extends State<EditProfileScreen> {
final _usernameController = TextEditingController();
final _bioController = TextEditingController();
final _usersApi = sl<UsersApi>();
final _userCache = sl<SettingsUserCache>();
UserResponse? _user;
bool _isLoading = true;
@@ -35,9 +37,21 @@ class _EditProfileScreenState extends State<EditProfileScreen> {
}
Future<void> _loadUser() async {
final cached = _userCache.cachedUser;
if (cached != null) {
setState(() {
_user = cached;
_usernameController.text = cached.username;
_bioController.text = cached.bio ?? '';
_isLoading = false;
});
return;
}
try {
final user = await _usersApi.getMe();
if (mounted) {
_userCache.set(user);
setState(() {
_user = user;
_usernameController.text = user.username;
@@ -91,7 +105,8 @@ class _EditProfileScreenState extends State<EditProfileScreen> {
username: newUsername,
bio: newBio.isEmpty ? null : newBio,
);
await _usersApi.updateMe(request);
final updatedUser = await _usersApi.updateMe(request);
_userCache.set(updatedUser);
if (mounted) {
Toast.show(context, '保存成功', type: ToastType.success);
@@ -1,18 +1,30 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:social_app/core/constants/app_constants.dart';
import 'package:social_app/core/di/injection.dart';
import 'package:social_app/core/router/app_routes.dart';
import 'package:social_app/core/theme/design_tokens.dart';
import 'package:social_app/shared/widgets/app_button.dart';
import 'package:social_app/shared/widgets/app_loading_indicator.dart';
import 'package:social_app/shared/widgets/app_pressable.dart';
import 'package:social_app/shared/widgets/destructive_action_sheet.dart';
import 'package:social_app/shared/widgets/toast/toast.dart';
import 'package:social_app/shared/widgets/toast/toast_type.dart';
import 'package:social_app/shared/utils/phone_display_formatter.dart';
import 'package:social_app/features/auth/presentation/bloc/auth_bloc.dart';
import 'package:social_app/features/auth/presentation/bloc/auth_event.dart';
import 'package:social_app/features/auth/presentation/bloc/auth_state.dart';
import 'package:social_app/features/friends/data/friends_api.dart';
import 'package:social_app/features/settings/data/settings_api.dart';
import 'package:social_app/features/settings/data/services/settings_user_cache.dart';
import 'package:social_app/features/users/data/models/user_response.dart';
import 'package:social_app/features/users/data/users_api.dart';
import '../widgets/settings_page_scaffold.dart';
const settingsProfileEditButtonKey = ValueKey('settings_profile_edit_button');
const settingsLogoutButtonKey = ValueKey('settings_logout_button');
class SettingsScreen extends StatefulWidget {
const SettingsScreen({super.key});
@@ -21,6 +33,10 @@ class SettingsScreen extends StatefulWidget {
}
class _SettingsScreenState extends State<SettingsScreen> {
final UsersApi _usersApi = sl<UsersApi>();
final FriendsApi _friendsApi = sl<FriendsApi>();
final SettingsUserCache _userCache = sl<SettingsUserCache>();
UserResponse? _user;
bool _isLoading = true;
int _friendsCount = 0;
@@ -29,39 +45,45 @@ class _SettingsScreenState extends State<SettingsScreen> {
@override
void initState() {
super.initState();
final cachedUser = _userCache.cachedUser;
if (cachedUser != null) {
_user = cachedUser;
_isLoading = false;
}
_loadData();
}
Future<void> _loadData() async {
try {
final usersApi = sl<UsersApi>();
final friendsApi = sl<FriendsApi>();
final results = await Future.wait([
usersApi.getMe(),
friendsApi.getFriends(),
]);
final user = results[0] as UserResponse;
final friends = results[1] as List<FriendResponse>;
final user = await _userCache.getOrLoad(_usersApi.getMe);
if (mounted) {
setState(() {
_user = user;
_friendsCount = friends.length;
_firstFriendName = friends.isNotEmpty
? friends.first.friend.username
: null;
_isLoading = false;
});
}
} catch (e) {
if (mounted) {
if (mounted && _user == null) {
setState(() {
_isLoading = false;
});
}
}
try {
final friends = await _friendsApi.getFriends();
if (mounted) {
setState(() {
_friendsCount = friends.length;
_firstFriendName = friends.isNotEmpty
? friends.first.friend.username
: null;
});
}
} catch (e) {
// Keep profile available even when contacts fail.
}
}
@override
@@ -73,17 +95,33 @@ class _SettingsScreenState extends State<SettingsScreen> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildProfileHero(),
const SizedBox(height: 16),
const SizedBox(height: AppSpacing.lg),
_buildQuickActions(context),
const SizedBox(height: 16),
const SizedBox(height: AppSpacing.lg),
_buildSubscriptionCard(),
const SizedBox(height: 16),
const SizedBox(height: AppSpacing.lg),
_buildMenuCard(context),
const SizedBox(height: AppSpacing.xl),
_buildLogoutAction(),
],
),
);
}
Widget _buildSectionLabel(String label) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xs),
child: Text(
label,
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.slate500,
),
),
);
}
Widget _buildProfileHero() {
if (_isLoading) {
return Container(
@@ -92,7 +130,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
padding: const EdgeInsets.all(AppSpacing.xl),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(24),
borderRadius: BorderRadius.circular(AppRadius.xxl),
),
child: const Center(child: AppLoadingIndicator(size: 22)),
);
@@ -110,109 +148,147 @@ class _SettingsScreenState extends State<SettingsScreen> {
gradient: const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [AppColors.white, Color(0xF8F9FCFF)],
colors: [AppColors.white, AppColors.surfaceInfoLight],
),
borderRadius: BorderRadius.circular(24),
border: Border.all(color: AppColors.borderSecondary),
boxShadow: const [
borderRadius: BorderRadius.circular(AppRadius.xxl),
border: Border.all(color: AppColors.borderTertiary),
boxShadow: [
BoxShadow(
color: Color(0x05000000),
blurRadius: 12,
offset: Offset(0, 3),
color: AppColors.blue100.withValues(alpha: 0.35),
blurRadius: 14,
offset: const Offset(0, 4),
),
],
),
child: Row(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
width: 64,
height: 64,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [AppColors.blue100, AppColors.blue50],
),
borderRadius: BorderRadius.circular(32),
boxShadow: [
BoxShadow(
color: Color.fromRGBO(
AppColors.blue400.r.toInt(),
AppColors.blue400.g.toInt(),
AppColors.blue400.b.toInt(),
0.2,
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: 64,
height: 64,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [AppColors.blue100, AppColors.blue50],
),
blurRadius: 12,
offset: const Offset(0, 4),
),
],
),
child: const Icon(Icons.person, size: 28, color: AppColors.blue600),
),
const SizedBox(width: AppSpacing.lg),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Text(
username,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.w700,
color: AppColors.slate900,
),
overflow: TextOverflow.ellipsis,
borderRadius: BorderRadius.circular(32),
boxShadow: [
BoxShadow(
color: Color.fromRGBO(
AppColors.blue400.r.toInt(),
AppColors.blue400.g.toInt(),
AppColors.blue400.b.toInt(),
0.2,
),
blurRadius: 12,
offset: const Offset(0, 4),
),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 5,
],
),
child: const Icon(
Icons.person,
size: 28,
color: AppColors.blue600,
),
),
const SizedBox(width: AppSpacing.lg),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
username,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.w700,
color: AppColors.slate900,
),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
AppColors.blue50,
AppColors.surfaceInfoLight,
],
),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: AppColors.borderQuaternary),
),
child: const Text(
'Free',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: AppColors.blue600,
),
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 6),
Text(
phone,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w500,
color: AppColors.slate500,
),
),
],
),
const SizedBox(height: 6),
Text(
phone,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w500,
color: AppColors.slate500,
),
const SizedBox(width: AppSpacing.md),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
AppPressable(
key: settingsProfileEditButtonKey,
onTap: _onTapEditProfile,
borderRadius: BorderRadius.circular(AppRadius.lg),
child: SizedBox(
width: AppSpacing.xl * 2,
height: AppSpacing.xl * 2,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Icon(
Icons.edit,
size: 14,
color: AppColors.slate500,
),
const SizedBox(height: 3),
Container(
width: 12,
height: 1.5,
decoration: BoxDecoration(
color: AppColors.slate400,
borderRadius: BorderRadius.circular(
AppRadius.full,
),
),
),
],
),
),
),
),
],
),
const SizedBox(height: AppSpacing.sm),
_buildFreeBadge(),
],
),
],
),
],
),
);
}
Widget _buildFreeBadge() {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [AppColors.blue50, AppColors.surfaceInfoLight],
),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: AppColors.borderQuaternary),
),
child: const Text(
'Free',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: AppColors.blue600,
),
),
);
}
String _buildFriendsSubtitle() {
if (_friendsCount == 0) {
return '暂无联系人';
@@ -232,17 +308,17 @@ class _SettingsScreenState extends State<SettingsScreen> {
iconColor: AppColors.blue500,
title: '联系人',
subtitle: _buildFriendsSubtitle(),
onTap: () => context.push('/contacts'),
onTap: () => context.push(AppRoutes.contactsList),
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: _buildActionCard(
icon: Icons.auto_awesome,
iconColor: const Color(0xFF8B5CF6),
iconColor: AppColors.violet500,
title: '周期计划',
subtitle: '已启用:会议提醒',
onTap: () => context.push('/settings/features'),
onTap: () => context.push(AppRoutes.settingsFeatures),
),
),
],
@@ -256,19 +332,21 @@ class _SettingsScreenState extends State<SettingsScreen> {
required String subtitle,
required VoidCallback onTap,
}) {
return GestureDetector(
return AppPressable(
onTap: onTap,
borderRadius: BorderRadius.circular(AppRadius.xl),
child: Container(
constraints: const BoxConstraints(minHeight: 136),
padding: const EdgeInsets.all(AppSpacing.lg),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(20),
borderRadius: BorderRadius.circular(AppRadius.xl),
border: Border.all(color: AppColors.borderSecondary),
boxShadow: const [
boxShadow: [
BoxShadow(
color: Color(0x04000000),
blurRadius: 6,
offset: Offset(0, 1),
color: AppColors.slate200.withValues(alpha: 0.45),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
@@ -323,15 +401,15 @@ class _SettingsScreenState extends State<SettingsScreen> {
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [AppColors.white, const Color(0xFFFAFBFF)],
colors: [AppColors.white, AppColors.surfaceInfoLight],
),
borderRadius: BorderRadius.circular(20),
border: Border.all(color: AppColors.borderSecondary),
boxShadow: const [
borderRadius: BorderRadius.circular(AppRadius.xl),
border: Border.all(color: AppColors.borderTertiary),
boxShadow: [
BoxShadow(
color: Color(0x03000000),
blurRadius: 6,
offset: Offset(0, 1),
color: AppColors.slate200.withValues(alpha: 0.4),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
@@ -419,7 +497,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
return Container(
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(16),
borderRadius: BorderRadius.circular(AppRadius.xl),
border: Border.all(color: AppColors.borderSecondary),
),
child: Column(
@@ -433,13 +511,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_buildMenuItem(
icon: Icons.bookmark,
title: '我的记忆',
onTap: () => context.push('/settings/memory'),
),
_buildDivider(),
_buildMenuItem(
icon: Icons.person,
title: '我的账户',
onTap: () => context.push('/settings/account'),
onTap: () => context.push(AppRoutes.settingsMemory),
),
_buildDivider(),
_buildMenuItem(
@@ -459,9 +531,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
String? trailing,
required VoidCallback onTap,
}) {
return GestureDetector(
return AppPressable(
onTap: onTap,
behavior: HitTestBehavior.opaque,
borderRadius: BorderRadius.circular(AppRadius.md),
child: Container(
height: 56,
padding: const EdgeInsets.symmetric(horizontal: 14),
@@ -515,6 +587,45 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
}
Future<void> _onTapEditProfile() async {
final changed = await context.push<bool>(AppRoutes.settingsEditProfile);
if (changed == true && mounted) {
final cached = _userCache.cachedUser;
if (cached != null) {
setState(() {
_user = cached;
});
}
}
}
Future<void> _onTapLogout() async {
final confirmed = await showDestructiveActionSheet(
context,
title: '退出登录',
message: '确定退出当前账户吗?',
confirmText: '确认退出',
);
if (!confirmed || !mounted) {
return;
}
_userCache.invalidate();
final authBloc = context.read<AuthBloc>();
authBloc.add(AuthLoggedOut());
try {
await authBloc.stream
.firstWhere((state) => state is AuthUnauthenticated)
.timeout(const Duration(seconds: 5));
} catch (_) {
if (!mounted) return;
Toast.show(context, '退出失败,请稍后重试', type: ToastType.error);
return;
}
if (!mounted) return;
context.go(AppRoutes.authLogin);
}
Future<void> _checkForUpdates() async {
try {
final settingsApi = sl<SettingsApi>();
@@ -566,4 +677,17 @@ class _SettingsScreenState extends State<SettingsScreen> {
Toast.show(context, '检查更新失败', type: ToastType.error);
}
}
Widget _buildLogoutAction() {
return SizedBox(
width: double.infinity,
height: 52,
child: AppButton(
key: settingsLogoutButtonKey,
text: '退出登录',
isOutlined: true,
onPressed: () => _onTapLogout(),
),
);
}
}
@@ -51,15 +51,7 @@ class SettingsPageScaffold extends StatelessWidget {
AppSpacing.xl,
AppSpacing.xl,
),
child: Container(
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.surfaceInfoLight,
borderRadius: BorderRadius.circular(AppRadius.xl),
border: Border.all(color: AppColors.borderTertiary),
),
child: footer,
),
child: footer,
),
],
),
@@ -59,6 +59,14 @@ class TodoApi {
return TodoResponse.fromJson(response.data);
}
Future<void> updateTodoPriority(String id, int priority) async {
try {
await _client.patch('$_prefix/$id', data: {'priority': priority});
} catch (_) {
// Ignore response parsing errors, just need to know if request succeeded
}
}
Future<TodoResponse> completeTodo(String id) async {
final response = await _client.post('$_prefix/$id/complete', data: {});
return TodoResponse.fromJson(response.data);
@@ -12,6 +12,7 @@ import '../../../../shared/widgets/full_screen_loading.dart';
import '../../../../shared/widgets/toast/toast.dart';
import '../../../../shared/widgets/toast/toast_type.dart';
import '../../../calendar/data/calendar_api.dart';
import '../../../calendar/data/models/schedule_item_model.dart';
import '../../data/todo_api.dart';
class TodoEditScreen extends StatefulWidget {
@@ -88,6 +89,7 @@ class _TodoEditScreenState extends State<TodoEditScreen> {
..clear()
..addAll(todo?.scheduleItems.map((item) => item.id) ?? const []);
_scheduleItems = scheduleItems
.where((item) => item.status == ScheduleStatus.active)
.map(
(item) => _ScheduleItemSimple(
id: item.id,
@@ -115,22 +117,29 @@ class _TodoEditScreenState extends State<TodoEditScreen> {
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.todoBg,
resizeToAvoidBottomInset: false,
body: SafeArea(
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [AppColors.homeBackgroundTop, AppColors.todoBg],
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => FocusScope.of(context).unfocus(),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [AppColors.homeBackgroundTop, AppColors.todoBg],
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
BackTitlePageHeader(
title: widget.isCreateMode ? '新建待办' : '编辑待办',
),
Expanded(child: _buildBody()),
_buildBottomAction(),
],
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
BackTitlePageHeader(title: widget.isCreateMode ? '新建待办' : '编辑待办'),
Expanded(child: _buildBody()),
_buildBottomAction(),
],
),
),
),
@@ -406,11 +415,6 @@ class _TodoEditScreenState extends State<TodoEditScreen> {
if (!mounted) {
return;
}
Toast.show(
context,
widget.isCreateMode ? '待办已创建' : '待办已更新',
type: ToastType.success,
);
context.pop(true);
} catch (error) {
if (!mounted) {
@@ -15,6 +15,7 @@ import '../../../../shared/widgets/toast/toast_type.dart';
import '../../../calendar/ui/calendar_state_manager.dart';
import '../../../calendar/ui/widgets/bottom_dock.dart';
import '../../data/todo_api.dart';
import '../widgets/todo_drag_item.dart';
class TodoQuadrantsScreen extends StatefulWidget {
const TodoQuadrantsScreen({super.key});
@@ -32,6 +33,78 @@ class _TodoQuadrantsScreenState extends State<TodoQuadrantsScreen> {
bool _loadingTodosRequest = false;
String? _error;
String? _draggingTodoId;
int? _dragTargetQuadrant;
int? _dragInsertIndex;
bool get _isDragging => _draggingTodoId != null;
void _onDragStart(String todoId) {
setState(() {
_draggingTodoId = todoId;
_dragTargetQuadrant = null;
_dragInsertIndex = null;
});
}
void _onDragEnd() {
setState(() {
_draggingTodoId = null;
_dragTargetQuadrant = null;
_dragInsertIndex = null;
});
}
void _onDragEnterQuadrant(int quadrant) {
setState(() {
_dragTargetQuadrant = quadrant;
});
}
void _onDragUpdateInsertIndex(int index) {
setState(() {
_dragInsertIndex = index;
});
}
Future<void> _onDrop(
String todoId,
int targetQuadrant,
int insertIndex,
) async {
final previousTodos = List<TodoResponse>.from(_todos);
try {
final todo = _todos.firstWhere((t) => t.id == todoId);
final sourceQuadrant = todo.priority;
if (sourceQuadrant == targetQuadrant) {
_onDragEnd();
return;
}
setState(() {
final index = _todos.indexWhere((t) => t.id == todoId);
if (index != -1) {
_todos[index] = _todos[index].copyWith(priority: targetQuadrant);
}
});
await _todoApi.updateTodoPriority(todoId, targetQuadrant);
} catch (e) {
if (!mounted) return;
setState(() {
_todos = previousTodos;
});
Toast.show(context, '移动失败', type: ToastType.error);
} finally {
if (mounted) _onDragEnd();
}
}
void _onDragLeave() {
// 清除高亮
}
@override
void initState() {
super.initState();
@@ -140,7 +213,7 @@ class _TodoQuadrantsScreenState extends State<TodoQuadrantsScreen> {
child: Column(
children: [
_buildHeader(),
Expanded(child: _buildContent()),
Expanded(child: _buildContent(withScroll: true)),
_buildBottomDock(),
],
),
@@ -205,7 +278,7 @@ class _TodoQuadrantsScreenState extends State<TodoQuadrantsScreen> {
);
}
Widget _buildContent() {
Widget _buildContent({bool withScroll = false}) {
if (_isLoading) {
return const FullScreenLoading();
}
@@ -214,58 +287,71 @@ class _TodoQuadrantsScreenState extends State<TodoQuadrantsScreen> {
return ErrorRetrySurface(message: '加载失败: $_error', onRetry: _loadTodos);
}
return Stack(
Widget content = Column(
mainAxisSize: MainAxisSize.min,
children: [
RefreshIndicator.noSpinner(
onRefresh: _onPullRefresh,
child: Padding(
padding: const EdgeInsets.only(
left: 16,
right: 16,
top: 4,
bottom: 96,
),
child: ListView(
children: [
_buildQuadrant(
title: '重要紧急',
textColor: AppColors.g1Text,
dividerColor: AppColors.g1Divider,
borderColor: AppColors.g1Border,
items: _importantUrgent,
onComplete: _completeTodo,
onTap: _navigateToDetail,
),
const SizedBox(height: 12),
_buildQuadrant(
title: '紧急不重要',
textColor: AppColors.g2Text,
dividerColor: AppColors.g2Divider,
borderColor: AppColors.g2Border,
items: _urgentNotImportant,
onComplete: _completeTodo,
onTap: _navigateToDetail,
),
const SizedBox(height: 12),
_buildQuadrant(
title: '重要不紧急',
textColor: AppColors.g3Text,
dividerColor: AppColors.g3Divider,
borderColor: AppColors.g3Border,
items: _importantNotUrgent,
onComplete: _completeTodo,
onTap: _navigateToDetail,
),
],
),
),
_buildQuadrant(
title: '重要紧急',
textColor: AppColors.g1Text,
dividerColor: AppColors.g1Divider,
borderColor: AppColors.g1Border,
items: _importantUrgent,
quadrantValue: 1,
onComplete: _completeTodo,
onTap: _navigateToDetail,
),
Align(
alignment: Alignment.topCenter,
child: AppPullRefreshFeedback(visible: _isPullRefreshing),
const SizedBox(height: 12),
_buildQuadrant(
title: '紧急不重要',
textColor: AppColors.g2Text,
dividerColor: AppColors.g2Divider,
borderColor: AppColors.g2Border,
items: _urgentNotImportant,
quadrantValue: 3,
onComplete: _completeTodo,
onTap: _navigateToDetail,
),
const SizedBox(height: 12),
_buildQuadrant(
title: '重要不紧急',
textColor: AppColors.g3Text,
dividerColor: AppColors.g3Divider,
borderColor: AppColors.g3Border,
items: _importantNotUrgent,
quadrantValue: 2,
onComplete: _completeTodo,
onTap: _navigateToDetail,
),
],
);
if (withScroll) {
return Stack(
children: [
RefreshIndicator.noSpinner(
onRefresh: _onPullRefresh,
child: SingleChildScrollView(
padding: const EdgeInsets.only(
left: 16,
right: 16,
top: 4,
bottom: 96,
),
child: content,
),
),
Align(
alignment: Alignment.topCenter,
child: AppPullRefreshFeedback(visible: _isPullRefreshing),
),
],
);
}
return Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
child: content,
);
}
Widget _buildQuadrant({
@@ -274,73 +360,132 @@ class _TodoQuadrantsScreenState extends State<TodoQuadrantsScreen> {
required Color dividerColor,
required Color borderColor,
required List<TodoResponse> items,
required int quadrantValue,
required Future<void> Function(TodoResponse) onComplete,
required void Function(TodoResponse) onTap,
}) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: AppColors.todoCardBg,
borderRadius: BorderRadius.circular(14),
border: Border.all(color: borderColor, width: 1),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
title,
style: TextStyle(
fontFamily: 'Inter',
fontSize: 15,
fontWeight: FontWeight.w700,
color: textColor,
),
),
Text(
'${items.length}',
style: TextStyle(
fontFamily: 'Inter',
fontSize: 12,
fontWeight: FontWeight.w700,
color: textColor,
),
),
],
),
const SizedBox(height: 8),
_buildQuadrantHeader(title, textColor, items.length),
Container(height: 1, color: dividerColor),
const SizedBox(height: 8),
if (items.isEmpty)
const Padding(
padding: EdgeInsets.symmetric(vertical: 16),
child: Center(
child: Text(
'暂无待办',
style: TextStyle(
fontFamily: 'Inter',
fontSize: 13,
color: AppColors.slate400,
Padding(
padding: const EdgeInsets.fromLTRB(6, 0, 6, 8),
child: DragTarget<String>(
onWillAcceptWithDetails: (details) {
_onDragEnterQuadrant(quadrantValue);
return true;
},
onAcceptWithDetails: (details) {
final parts = details.data.split(':');
final todoId = parts[0];
_onDrop(todoId, quadrantValue, 0);
},
onLeave: (_) {
_onDragLeave();
},
builder: (context, candidateData, rejectedData) {
final isDragOver = candidateData.isNotEmpty;
return Container(
decoration: BoxDecoration(
color: isDragOver
? AppColors.blue50.withValues(alpha: 0.3)
: Colors.transparent,
borderRadius: BorderRadius.circular(8),
border: isDragOver
? Border.all(color: AppColors.blue400, width: 2)
: null,
),
),
),
)
else
...items.map(
(item) => _TodoItemWidget(
item: item,
onComplete: () => onComplete(item),
onTap: () => onTap(item),
),
child: items.isEmpty
? SizedBox(
height: 60,
child: Center(
child: Text(
'暂无待办',
style: TextStyle(
fontFamily: 'Inter',
fontSize: 13,
color: AppColors.slate400,
),
),
),
)
: _buildQuadrantItemList(
items,
quadrantValue,
onComplete,
onTap,
),
);
},
),
),
],
),
);
}
Widget _buildQuadrantHeader(String title, Color textColor, int itemCount) {
return Padding(
padding: const EdgeInsets.fromLTRB(10, 10, 10, 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
title,
style: TextStyle(
fontFamily: 'Inter',
fontSize: 15,
fontWeight: FontWeight.w700,
color: textColor,
),
),
Text(
'${itemCount}',
style: TextStyle(
fontFamily: 'Inter',
fontSize: 12,
fontWeight: FontWeight.w700,
color: textColor,
),
),
],
),
);
}
Widget _buildQuadrantItemList(
List<TodoResponse> items,
int quadrantValue,
Future<void> Function(TodoResponse) onComplete,
void Function(TodoResponse) onTap,
) {
return Column(
mainAxisSize: MainAxisSize.min,
children: items.map((item) {
return TodoDragItem(
todo: item,
quadrant: quadrantValue,
onDragStarted: () => _onDragStart(item.id),
onDragEnd: _onDragEnd,
child: _TodoItemWidget(
item: item,
onComplete: () => onComplete(item),
onTap: () => onTap(item),
),
);
}).toList(),
);
}
Widget _buildBottomDock() {
return BottomDock(
activeTab: DockTab.todo,
@@ -0,0 +1,74 @@
import 'package:flutter/material.dart';
import 'package:social_app/core/theme/design_tokens.dart';
import 'package:social_app/features/todo/data/todo_api.dart';
class TodoDragItem extends StatelessWidget {
final TodoResponse todo;
final int quadrant;
final VoidCallback onDragStarted;
final VoidCallback onDragEnd;
final Widget child;
const TodoDragItem({
super.key,
required this.todo,
required this.quadrant,
required this.onDragStarted,
required this.onDragEnd,
required this.child,
});
@override
Widget build(BuildContext context) {
return LongPressDraggable<String>(
data: '${todo.id}:$quadrant',
delay: const Duration(milliseconds: 150),
feedback: Material(
elevation: 8,
borderRadius: BorderRadius.circular(AppRadius.md),
child: Transform.scale(
scale: 1.03,
child: SizedBox(width: 280, child: _buildDragFeedback()),
),
),
childWhenDragging: AnimatedOpacity(
duration: const Duration(milliseconds: 100),
opacity: 0.3,
child: child,
),
onDragStarted: onDragStarted,
onDragEnd: (_) => onDragEnd(),
child: child,
);
}
Widget _buildDragFeedback() {
return Container(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.md,
vertical: AppSpacing.sm,
),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(AppRadius.md),
boxShadow: [
BoxShadow(
color: AppColors.slate400.withValues(alpha: 0.3),
blurRadius: 12,
offset: const Offset(0, 4),
),
],
),
child: Text(
todo.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.slate700,
),
),
);
}
}
+21
View File
@@ -6,6 +6,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'core/constants/app_constants.dart';
import 'core/di/injection.dart';
import 'core/notifications/local_notification_service.dart';
import 'core/notifications/reminder_notification_callbacks.dart';
import 'core/router/app_router.dart';
import 'core/startup/auth_session_bootstrapper.dart';
import 'core/theme/app_theme.dart';
@@ -14,12 +15,18 @@ import 'features/auth/presentation/bloc/auth_event.dart';
import 'features/auth/presentation/bloc/auth_state.dart';
import 'features/calendar/data/services/calendar_service.dart';
import 'features/calendar/reminders/reminder_action_executor.dart';
import 'features/calendar/reminders/ui/reminder_foreground_presenter.dart';
import 'features/chat/presentation/bloc/chat_bloc.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await configureDependencies();
await AppConstants.init();
final rootNavigatorKey = GlobalKey<NavigatorState>();
final reminderForegroundPresenter = ReminderForegroundPresenter(
navigatorKey: rootNavigatorKey,
executor: sl<ReminderActionExecutor>(),
);
sl<LocalNotificationService>().bindActionHandler(({
required action,
required payload,
@@ -29,6 +36,9 @@ void main() async {
payload: payload,
);
});
sl<LocalNotificationService>().bindInAppReminderHandler(
reminderForegroundPresenter.present,
);
await sl<LocalNotificationService>().initialize();
final authBloc = sl<AuthBloc>();
@@ -37,6 +47,7 @@ void main() async {
runApp(
LinksyApp(
authBloc: authBloc,
rootNavigatorKey: rootNavigatorKey,
sessionBootstrapper: AuthSessionBootstrapper(
calendarService: sl<CalendarService>(),
notificationService: sl<LocalNotificationService>(),
@@ -44,15 +55,25 @@ void main() async {
),
),
);
WidgetsBinding.instance.addPostFrameCallback((_) {
unawaited(
ReminderNotificationCallbacks.bindResponseHandler(
sl<LocalNotificationService>().handleNotificationResponse,
),
);
});
}
class LinksyApp extends StatelessWidget {
final AuthBloc authBloc;
final GlobalKey<NavigatorState> rootNavigatorKey;
final AuthSessionBootstrapper sessionBootstrapper;
const LinksyApp({
super.key,
required this.authBloc,
required this.rootNavigatorKey,
required this.sessionBootstrapper,
});
@@ -0,0 +1,117 @@
import 'package:flutter/material.dart';
import '../../core/theme/design_tokens.dart';
import 'app_button.dart';
class AppSelectionItem<T> {
const AppSelectionItem({required this.value, required this.label});
final T value;
final String label;
}
Future<T?> showAppSelectionSheet<T>(
BuildContext context, {
required String title,
required List<AppSelectionItem<T>> items,
required T? selectedValue,
}) async {
final result = await showModalBottomSheet<T>(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (sheetContext) {
return SafeArea(
top: false,
child: Container(
margin: const EdgeInsets.fromLTRB(
AppSpacing.md,
AppSpacing.none,
AppSpacing.md,
AppSpacing.md,
),
padding: const EdgeInsets.symmetric(vertical: AppSpacing.lg),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(AppRadius.xl),
border: Border.all(color: AppColors.borderSecondary),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
child: Text(
title,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.w700,
color: AppColors.slate900,
),
),
),
const SizedBox(height: AppSpacing.md),
...items.map((item) {
final isSelected = item.value == selectedValue;
return _buildItem(
sheetContext,
item: item,
isSelected: isSelected,
);
}),
const SizedBox(height: AppSpacing.sm),
const Divider(height: 1, color: AppColors.border),
const SizedBox(height: AppSpacing.sm),
Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
child: SizedBox(
height: 48,
child: AppButton(
text: '取消',
isOutlined: true,
onPressed: () => Navigator.of(sheetContext).pop(),
),
),
),
],
),
),
);
},
);
return result;
}
Widget _buildItem<T>(
BuildContext sheetContext, {
required AppSelectionItem<T> item,
required bool isSelected,
}) {
return InkWell(
onTap: () => Navigator.of(sheetContext).pop(item.value),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg,
vertical: AppSpacing.md,
),
child: Row(
children: [
Expanded(
child: Text(
item.label,
style: TextStyle(
fontSize: 15,
fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
color: isSelected ? AppColors.blue600 : AppColors.slate800,
),
),
),
if (isSelected)
const Icon(Icons.check, size: 20, color: AppColors.blue600),
],
),
),
);
}
@@ -8,12 +8,14 @@ class DetailHeaderActionItem<T> {
required this.label,
required this.icon,
this.isDestructive = false,
this.enabled = true,
});
final T value;
final String label;
final IconData icon;
final bool isDestructive;
final bool enabled;
}
class DetailHeaderActionMenu<T> extends StatefulWidget {
@@ -141,7 +143,7 @@ class _DetailHeaderActionMenuState<T> extends State<DetailHeaderActionMenu<T>> {
Widget _buildMenuItem(DetailHeaderActionItem<T> item) {
final textColor = item.isDestructive
? AppColors.red500
: AppColors.slate700;
: (item.enabled ? AppColors.slate700 : AppColors.slate400);
final pressedColor = item.isDestructive
? AppColors.feedbackErrorSurface
: AppColors.surfaceInfoLight;
@@ -152,9 +154,9 @@ class _DetailHeaderActionMenuState<T> extends State<DetailHeaderActionMenu<T>> {
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(AppRadius.md),
splashColor: pressedColor,
highlightColor: pressedColor,
onTap: () => _handleSelect(item.value),
splashColor: item.enabled ? pressedColor : Colors.transparent,
highlightColor: item.enabled ? pressedColor : Colors.transparent,
onTap: item.enabled ? () => _handleSelect(item.value) : null,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
child: Row(
@@ -0,0 +1,78 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:social_app/features/calendar/reminders/reminder_action_dedupe_store.dart';
void main() {
const dedupeKey = 'calendar_reminder_action_dedupe_v1';
setUp(() {
SharedPreferences.setMockInitialValues({});
});
test('markIfNew returns true first and false for duplicate id', () async {
final prefs = await SharedPreferences.getInstance();
final store = ReminderActionDedupeStore(prefs);
expect(await store.markIfNew('action_1'), isTrue);
expect(await store.markIfNew('action_1'), isFalse);
});
test('markIfNew dedupes after store re-initialization', () async {
final firstPrefs = await SharedPreferences.getInstance();
final firstStore = ReminderActionDedupeStore(firstPrefs);
expect(await firstStore.markIfNew('action_restart'), isTrue);
final secondPrefs = await SharedPreferences.getInstance();
final secondStore = ReminderActionDedupeStore(secondPrefs);
expect(await secondStore.markIfNew('action_restart'), isFalse);
});
test('markIfNew trims history to max capacity', () async {
final prefs = await SharedPreferences.getInstance();
final store = ReminderActionDedupeStore(prefs);
for (var i = 0; i < 513; i++) {
expect(await store.markIfNew('action_$i'), isTrue);
}
final stored = prefs.getStringList(dedupeKey)!;
expect(stored.length, 512);
expect(stored.first, 'action_1');
expect(stored.last, 'action_512');
});
test(
'markIfNew is serialized and does not return true twice in parallel',
() async {
final prefs = await SharedPreferences.getInstance();
final store = ReminderActionDedupeStore(
prefs,
setStringList: (key, value) async {
await Future<void>.delayed(const Duration(milliseconds: 20));
return prefs.setStringList(key, value);
},
);
final results = await Future.wait<bool>([
store.markIfNew('parallel_action'),
store.markIfNew('parallel_action'),
]);
expect(results.where((item) => item).length, 1);
expect(results.where((item) => !item).length, 1);
},
);
test('markIfNew returns false when persistence write fails', () async {
final prefs = await SharedPreferences.getInstance();
final store = ReminderActionDedupeStore(
prefs,
setStringList: (key, value) async => false,
);
expect(await store.markIfNew('action_write_fail'), isFalse);
expect(prefs.getStringList(dedupeKey), isNull);
});
}
@@ -33,7 +33,7 @@ void main() {
);
});
test('cancel archives remotely and cancels local reminder', () async {
test('archive archives remotely and cancels local reminder', () async {
when(
() => notificationService.cancelEventReminder('evt_1'),
).thenAnswer((_) async {});
@@ -42,7 +42,7 @@ void main() {
).thenAnswer((_) async => null);
await executor.handleAction(
action: ReminderAction.cancel,
action: ReminderAction.archive,
payload: ReminderPayload(
eventId: 'evt_1',
title: 'sync',
@@ -66,7 +66,7 @@ void main() {
).thenThrow(Exception('offline'));
await executor.handleAction(
action: ReminderAction.cancel,
action: ReminderAction.archive,
payload: ReminderPayload(
eventId: 'evt_1',
title: 'sync',
@@ -114,4 +114,60 @@ void main() {
).called(1);
verifyNever(() => calendarService.archiveEvent(any()));
});
test('fromValue throws on unknown action', () {
expect(
() => ReminderAction.fromValue('unknown_action'),
throwsA(isA<ArgumentError>()),
);
});
test(
'aggregate action falls back to eventId when aggregateIds is empty',
() async {
when(
() => notificationService.cancelEventReminder('evt_fallback'),
).thenAnswer((_) async {});
when(
() => calendarService.archiveEvent('evt_fallback'),
).thenAnswer((_) async => null);
await executor.handleAction(
action: ReminderAction.archive,
payload: ReminderPayload(
eventId: 'evt_fallback',
title: 'sync',
startAt: DateTime.parse('2026-03-18T16:00:00+08:00'),
timezone: 'Asia/Shanghai',
mode: ReminderPayloadMode.aggregate,
aggregateIds: const <String>[],
),
);
verify(
() => notificationService.cancelEventReminder('evt_fallback'),
).called(1);
verify(() => calendarService.archiveEvent('evt_fallback')).called(1);
},
);
test('replay keeps pending item when targetStatus is not archived', () async {
const opId = 'op_non_archived';
await outboxStore.enqueue(
ReminderOutboxItem(
opId: opId,
eventId: 'evt_1',
action: ReminderAction.archive,
targetStatus: 'ignored',
occurredAt: DateTime.parse('2026-03-18T16:00:00+08:00'),
),
);
await executor.replayPendingActions();
final pending = await outboxStore.listPending();
expect(pending.length, 1);
expect(pending.first.opId, opId);
verifyNever(() => calendarService.archiveEvent(any()));
});
}
@@ -0,0 +1,41 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:social_app/features/calendar/reminders/ui/widgets/reminder_action_sheet.dart';
void main() {
Future<void> pumpSheet(
WidgetTester tester, {
required VoidCallback onSnooze,
required VoidCallback onArchive,
}) {
return tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ReminderActionSheet(onSnooze: onSnooze, onArchive: onArchive),
),
),
);
}
testWidgets('tap snooze button triggers onSnooze', (tester) async {
var snoozed = false;
await pumpSheet(tester, onSnooze: () => snoozed = true, onArchive: () {});
await tester.tap(find.text('稍后提醒'));
await tester.pump();
expect(snoozed, isTrue);
});
testWidgets('tap archive button triggers onArchive', (tester) async {
var archived = false;
await pumpSheet(tester, onSnooze: () {}, onArchive: () => archived = true);
await tester.tap(find.text('归档'));
await tester.pump();
expect(archived, isTrue);
});
}
@@ -0,0 +1,123 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:social_app/features/calendar/reminders/reminder_cold_start_queue.dart';
void main() {
test('replays queued actions in enqueue order', () async {
final queue = ReminderColdStartQueue();
final events = <String>[];
queue.enqueue(() async {
await Future<void>.delayed(const Duration(milliseconds: 20));
events.add('first');
});
queue.enqueue(() async {
events.add('second');
});
queue.enqueue(() async {
events.add('third');
});
await queue.replay();
expect(events, <String>['first', 'second', 'third']);
});
test('single failure does not block following queued actions', () async {
final queue = ReminderColdStartQueue();
final events = <String>[];
final errors = <Object>[];
queue.enqueue(() async {
events.add('before');
});
queue.enqueue(() async {
throw StateError('boom');
});
queue.enqueue(() async {
events.add('after');
});
final observableQueue = ReminderColdStartQueue(
onTaskError: (Object error, StackTrace _) {
errors.add(error);
},
);
observableQueue.enqueue(() async {
throw StateError('boom_observable');
});
await queue.replay();
await observableQueue.replay();
expect(events, <String>['before', 'after']);
expect(errors.length, 1);
expect(errors.first, isA<StateError>());
});
test('concurrent replay calls join the same in-flight replay', () async {
final queue = ReminderColdStartQueue();
final taskGate = Completer<void>();
var runCount = 0;
var secondReplayCompleted = false;
queue.enqueue(() async {
runCount += 1;
await taskGate.future;
});
final firstReplay = queue.replay();
final secondReplay = queue.replay().then((_) {
secondReplayCompleted = true;
});
await Future<void>.delayed(const Duration(milliseconds: 10));
expect(secondReplayCompleted, isFalse);
taskGate.complete();
await Future.wait(<Future<void>>[firstReplay, secondReplay]);
expect(runCount, 1);
expect(secondReplayCompleted, isTrue);
});
test('replay on empty queue does not block future enqueued tasks', () async {
final queue = ReminderColdStartQueue();
final events = <String>[];
await queue.replay();
queue.enqueue(() async {
events.add('after_empty_replay');
});
await queue.replay();
expect(events, <String>['after_empty_replay']);
});
test('task-triggered replay reuses in-flight replay and completes', () async {
final queue = ReminderColdStartQueue();
final events = <String>[];
var nestedReplayCompleted = false;
queue.enqueue(() async {
events.add('first');
queue.replay().then((_) {
nestedReplayCompleted = true;
});
});
queue.enqueue(() async {
events.add('second');
});
await queue.replay();
await Future<void>.delayed(Duration.zero);
expect(events, <String>['first', 'second']);
expect(nestedReplayCompleted, isTrue);
});
}
@@ -0,0 +1,146 @@
import 'dart:convert';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:social_app/core/notifications/local_notification_service.dart';
import 'package:social_app/core/notifications/reminder_notification_callbacks.dart';
import 'package:social_app/features/calendar/reminders/models/reminder_action.dart';
import 'package:social_app/features/calendar/reminders/models/reminder_payload.dart';
class MockFlutterLocalNotificationsPlugin extends Mock
implements FlutterLocalNotificationsPlugin {}
void main() {
setUpAll(() {
registerFallbackValue(
const InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
iOS: DarwinInitializationSettings(),
),
);
});
late MockFlutterLocalNotificationsPlugin plugin;
late LocalNotificationService service;
late List<ReminderAction> handledActions;
late List<ReminderPayload> presentedPayloads;
DidReceiveNotificationResponseCallback? callback;
setUp(() async {
SharedPreferences.setMockInitialValues({});
plugin = MockFlutterLocalNotificationsPlugin();
service = LocalNotificationService(plugin: plugin);
handledActions = <ReminderAction>[];
presentedPayloads = <ReminderPayload>[];
when(
() => plugin.initialize(
any(),
onDidReceiveNotificationResponse: any(
named: 'onDidReceiveNotificationResponse',
),
onDidReceiveBackgroundNotificationResponse: any(
named: 'onDidReceiveBackgroundNotificationResponse',
),
),
).thenAnswer((invocation) async {
callback =
invocation.namedArguments[#onDidReceiveNotificationResponse]
as DidReceiveNotificationResponseCallback?;
return true;
});
when(
() => plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>(),
).thenReturn(null);
when(
() => plugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>(),
).thenReturn(null);
service.bindActionHandler(({required action, required payload}) async {
handledActions.add(action);
});
service.bindInAppReminderHandler((payload) async {
presentedPayloads.add(payload);
});
await ReminderNotificationCallbacks.bindResponseHandler(
service.handleNotificationResponse,
);
await service.initialize();
});
test('cancel action from system notification maps to archive', () async {
callback!(
NotificationResponse(
notificationResponseType:
NotificationResponseType.selectedNotificationAction,
id: 101,
actionId: 'cancel',
payload: jsonEncode(
ReminderPayload(
eventId: 'evt_1',
title: 'sync',
startAt: DateTime.parse('2026-03-19T10:00:00+08:00'),
timezone: 'Asia/Shanghai',
).toJson(),
),
),
);
await Future<void>.delayed(Duration.zero);
expect(handledActions, [ReminderAction.archive]);
});
test('duplicate notification response is handled only once', () async {
final response = NotificationResponse(
notificationResponseType:
NotificationResponseType.selectedNotificationAction,
id: 201,
actionId: 'cancel',
payload: jsonEncode(
ReminderPayload(
eventId: 'evt_2',
title: 'retro',
startAt: DateTime.parse('2026-03-19T11:00:00+08:00'),
timezone: 'Asia/Shanghai',
).toJson(),
),
);
callback!(response);
callback!(response);
await Future<void>.delayed(Duration.zero);
expect(handledActions, [ReminderAction.archive]);
});
test('notification body tap forwards payload to in-app presenter', () async {
callback!(
NotificationResponse(
notificationResponseType: NotificationResponseType.selectedNotification,
id: 301,
payload: jsonEncode(
ReminderPayload(
eventId: 'evt_3',
title: 'daily sync',
startAt: DateTime.parse('2026-03-19T12:00:00+08:00'),
timezone: 'Asia/Shanghai',
).toJson(),
),
),
);
await Future<void>.delayed(Duration.zero);
expect(presentedPayloads.map((item) => item.eventId), ['evt_3']);
expect(handledActions, isEmpty);
});
}
@@ -0,0 +1,142 @@
import 'dart:io';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:social_app/core/notifications/reminder_notification_callbacks.dart';
void main() {
setUp(() async {
SharedPreferences.setMockInitialValues({});
await ReminderNotificationCallbacks.resetForTest();
});
test('contains top-level vm entry-point background callback', () async {
final source = await File(
'lib/core/notifications/reminder_notification_callbacks.dart',
).readAsString();
expect(source, contains("@pragma('vm:entry-point')"));
expect(source, contains('Future<void> reminderNotificationTapBackground('));
});
test(
'dispatches foreground and background responses to bound handler',
() async {
final handledIds = <int?>[];
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
handledIds.add(response.id);
});
await ReminderNotificationCallbacks.onForegroundResponse(
NotificationResponse(
notificationResponseType:
NotificationResponseType.selectedNotificationAction,
id: 10,
),
);
await reminderNotificationTapBackground(
NotificationResponse(
notificationResponseType:
NotificationResponseType.selectedNotificationAction,
id: 20,
),
);
expect(handledIds, <int?>[10, 20]);
},
);
test(
'queues background response when handler is unbound and drains later',
() async {
await reminderNotificationTapBackground(
NotificationResponse(
notificationResponseType:
NotificationResponseType.selectedNotificationAction,
id: 99,
),
);
final handledIds = <int?>[];
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
handledIds.add(response.id);
});
expect(handledIds, <int?>[99]);
},
);
test(
'queues foreground response when handler is unbound and drains later',
() async {
await ReminderNotificationCallbacks.onForegroundResponse(
NotificationResponse(
notificationResponseType:
NotificationResponseType.selectedNotificationAction,
id: 55,
),
);
final handledIds = <int?>[];
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
handledIds.add(response.id);
});
expect(handledIds, <int?>[55]);
},
);
test('failed pending item stays queued for next bind retry', () async {
await reminderNotificationTapBackground(
NotificationResponse(
notificationResponseType:
NotificationResponseType.selectedNotificationAction,
id: 77,
),
);
var firstAttempt = true;
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
if (firstAttempt) {
firstAttempt = false;
throw Exception('temporary failure');
}
});
final handledIds = <int?>[];
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
handledIds.add(response.id);
});
expect(handledIds, <int?>[77]);
});
test(
'background handler failure while bound is enqueued for retry',
() async {
var firstAttempt = true;
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
if (firstAttempt) {
firstAttempt = false;
throw Exception('temporary failure');
}
});
await reminderNotificationTapBackground(
NotificationResponse(
notificationResponseType:
NotificationResponseType.selectedNotificationAction,
id: 123,
),
);
final handledIds = <int?>[];
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
handledIds.add(response.id);
});
expect(handledIds, <int?>[123]);
},
);
}
@@ -0,0 +1,392 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:social_app/core/notifications/local_notification_service.dart';
import 'package:social_app/features/calendar/data/models/schedule_item_model.dart';
import 'package:timezone/data/latest.dart' as tz_data;
import 'package:timezone/timezone.dart' as tz;
class MockFlutterLocalNotificationsPlugin extends Mock
implements FlutterLocalNotificationsPlugin {}
class MockAndroidFlutterLocalNotificationsPlugin extends Mock
implements AndroidFlutterLocalNotificationsPlugin {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() {
tz_data.initializeTimeZones();
registerFallbackValue(tz.TZDateTime.now(tz.local));
registerFallbackValue(const NotificationDetails());
registerFallbackValue(
const InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
iOS: DarwinInitializationSettings(),
),
);
});
setUp(() {
SharedPreferences.setMockInitialValues({});
debugDefaultTargetPlatformOverride = TargetPlatform.android;
});
tearDown(() {
debugDefaultTargetPlatformOverride = null;
});
test(
'tracks fallback when Android notifications permission is denied',
() async {
final plugin = MockFlutterLocalNotificationsPlugin();
final androidImpl = MockAndroidFlutterLocalNotificationsPlugin();
final fallbackEvents = <Map<String, String>>[];
when(
() => plugin.initialize(
any(),
onDidReceiveNotificationResponse: any(
named: 'onDidReceiveNotificationResponse',
),
onDidReceiveBackgroundNotificationResponse: any(
named: 'onDidReceiveBackgroundNotificationResponse',
),
),
).thenAnswer((_) async => true);
when(
() => plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>(),
).thenReturn(androidImpl);
when(
() => plugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>(),
).thenReturn(null);
when(
() => androidImpl.requestNotificationsPermission(),
).thenAnswer((_) async => false);
when(
() => androidImpl.requestExactAlarmsPermission(),
).thenAnswer((_) async => true);
when(
() => androidImpl.requestFullScreenIntentPermission(),
).thenAnswer((_) async => true);
when(
() => androidImpl.areNotificationsEnabled(),
).thenAnswer((_) async => false);
final service = LocalNotificationService(
plugin: plugin,
permissionFallbackTracker:
({
required actionExecutionId,
required permissionState,
required appLifecycleState,
required platform,
}) {
fallbackEvents.add({
'actionExecutionId': actionExecutionId,
'permissionState': permissionState,
'appLifecycleState': appLifecycleState,
'platform': platform,
});
},
);
await service.initialize();
expect(fallbackEvents.length, 1);
expect(fallbackEvents.first['permissionState'], 'denied');
expect(fallbackEvents.first['platform'], 'android');
},
);
test(
'skips reminder scheduling when Android notifications are denied',
() async {
final plugin = MockFlutterLocalNotificationsPlugin();
final androidImpl = MockAndroidFlutterLocalNotificationsPlugin();
when(
() => plugin.initialize(
any(),
onDidReceiveNotificationResponse: any(
named: 'onDidReceiveNotificationResponse',
),
onDidReceiveBackgroundNotificationResponse: any(
named: 'onDidReceiveBackgroundNotificationResponse',
),
),
).thenAnswer((_) async => true);
when(
() => plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>(),
).thenReturn(androidImpl);
when(
() => plugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>(),
).thenReturn(null);
when(
() => androidImpl.requestNotificationsPermission(),
).thenAnswer((_) async => false);
when(
() => androidImpl.requestExactAlarmsPermission(),
).thenAnswer((_) async => true);
when(
() => androidImpl.requestFullScreenIntentPermission(),
).thenAnswer((_) async => true);
when(
() => androidImpl.areNotificationsEnabled(),
).thenAnswer((_) async => false);
final service = LocalNotificationService(plugin: plugin);
final event = ScheduleItemModel(
id: 'evt_1',
ownerId: 'u1',
title: 'sync',
startAt: DateTime.now().add(const Duration(minutes: 20)),
endAt: DateTime.now().add(const Duration(minutes: 50)),
metadata: ScheduleMetadata(reminderMinutes: 15),
);
await service.upsertEventReminder(event);
verifyNever(() => plugin.pendingNotificationRequests());
},
);
test(
'dispatches in-app reminder callback when notifications are denied',
() async {
final plugin = MockFlutterLocalNotificationsPlugin();
final androidImpl = MockAndroidFlutterLocalNotificationsPlugin();
final presentedEventIds = <String>[];
when(
() => plugin.initialize(
any(),
onDidReceiveNotificationResponse: any(
named: 'onDidReceiveNotificationResponse',
),
onDidReceiveBackgroundNotificationResponse: any(
named: 'onDidReceiveBackgroundNotificationResponse',
),
),
).thenAnswer((_) async => true);
when(
() => plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>(),
).thenReturn(androidImpl);
when(
() => plugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>(),
).thenReturn(null);
when(
() => androidImpl.requestNotificationsPermission(),
).thenAnswer((_) async => false);
when(
() => androidImpl.requestExactAlarmsPermission(),
).thenAnswer((_) async => true);
when(
() => androidImpl.requestFullScreenIntentPermission(),
).thenAnswer((_) async => true);
when(
() => androidImpl.areNotificationsEnabled(),
).thenAnswer((_) async => false);
final service = LocalNotificationService(plugin: plugin);
service.bindInAppReminderHandler((payload) async {
presentedEventIds.add(payload.eventId);
});
final event = ScheduleItemModel(
id: 'evt_2',
ownerId: 'u1',
title: 'retro',
startAt: DateTime.now().add(const Duration(minutes: 20)),
endAt: DateTime.now().add(const Duration(minutes: 50)),
metadata: ScheduleMetadata(reminderMinutes: 15),
);
await service.scheduleReminderAt(
event,
DateTime.now().add(const Duration(milliseconds: 20)),
);
await Future<void>.delayed(const Duration(milliseconds: 100));
expect(presentedEventIds, contains('evt_2'));
verifyNever(
() => plugin.zonedSchedule(
any(),
any(),
any(),
any(),
any(),
payload: any(named: 'payload'),
androidScheduleMode: any(named: 'androidScheduleMode'),
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
),
);
},
);
test('rebuild twice only dispatches one aggregate in-app fallback', () async {
final plugin = MockFlutterLocalNotificationsPlugin();
final androidImpl = MockAndroidFlutterLocalNotificationsPlugin();
final presentedPayloads = <String>[];
when(
() => plugin.initialize(
any(),
onDidReceiveNotificationResponse: any(
named: 'onDidReceiveNotificationResponse',
),
onDidReceiveBackgroundNotificationResponse: any(
named: 'onDidReceiveBackgroundNotificationResponse',
),
),
).thenAnswer((_) async => true);
when(
() => plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>(),
).thenReturn(androidImpl);
when(
() => plugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>(),
).thenReturn(null);
when(
() => androidImpl.requestNotificationsPermission(),
).thenAnswer((_) async => false);
when(
() => androidImpl.requestExactAlarmsPermission(),
).thenAnswer((_) async => true);
when(
() => androidImpl.requestFullScreenIntentPermission(),
).thenAnswer((_) async => true);
when(
() => androidImpl.areNotificationsEnabled(),
).thenAnswer((_) async => false);
final service = LocalNotificationService(plugin: plugin);
service.bindInAppReminderHandler((payload) async {
presentedPayloads.add(payload.title);
});
final startAt = DateTime.now().add(const Duration(milliseconds: 50));
final event1 = ScheduleItemModel(
id: 'evt_a',
ownerId: 'u1',
title: 'evt_a',
startAt: startAt,
endAt: startAt.add(const Duration(minutes: 30)),
metadata: ScheduleMetadata(reminderMinutes: 0),
);
final event2 = ScheduleItemModel(
id: 'evt_b',
ownerId: 'u1',
title: 'evt_b',
startAt: startAt,
endAt: startAt.add(const Duration(minutes: 30)),
metadata: ScheduleMetadata(reminderMinutes: 0),
);
await service.rebuildUpcomingReminders([event1, event2]);
await service.rebuildUpcomingReminders([event1, event2]);
await Future<void>.delayed(const Duration(milliseconds: 180));
expect(
presentedPayloads.where((title) => title.contains('你有2个日程提醒')).length,
1,
);
});
test(
'rebuild clears stale in-app fallback timers for removed events',
() async {
final plugin = MockFlutterLocalNotificationsPlugin();
final androidImpl = MockAndroidFlutterLocalNotificationsPlugin();
final presentedEventIds = <String>[];
when(
() => plugin.initialize(
any(),
onDidReceiveNotificationResponse: any(
named: 'onDidReceiveNotificationResponse',
),
onDidReceiveBackgroundNotificationResponse: any(
named: 'onDidReceiveBackgroundNotificationResponse',
),
),
).thenAnswer((_) async => true);
when(
() => plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>(),
).thenReturn(androidImpl);
when(
() => plugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>(),
).thenReturn(null);
when(
() => androidImpl.requestNotificationsPermission(),
).thenAnswer((_) async => false);
when(
() => androidImpl.requestExactAlarmsPermission(),
).thenAnswer((_) async => true);
when(
() => androidImpl.requestFullScreenIntentPermission(),
).thenAnswer((_) async => true);
when(
() => androidImpl.areNotificationsEnabled(),
).thenAnswer((_) async => false);
final service = LocalNotificationService(plugin: plugin);
service.bindInAppReminderHandler((payload) async {
presentedEventIds.add(payload.eventId);
});
final startAt = DateTime.now().add(const Duration(milliseconds: 80));
final staleEvent = ScheduleItemModel(
id: 'evt_stale',
ownerId: 'u1',
title: 'evt_stale',
startAt: startAt,
endAt: startAt.add(const Duration(minutes: 20)),
metadata: ScheduleMetadata(reminderMinutes: 0),
);
await service.rebuildUpcomingReminders([staleEvent]);
await service.rebuildUpcomingReminders(const <ScheduleItemModel>[]);
await Future<void>.delayed(const Duration(milliseconds: 220));
expect(presentedEventIds, isNot(contains('evt_stale')));
},
);
}
@@ -0,0 +1,60 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:social_app/features/calendar/reminders/ui/reminder_presentation_coordinator.dart';
void main() {
test('blocks foreground presentation when app is not active', () {
final coordinator = ReminderPresentationCoordinator();
final hiddenDecision = coordinator.shouldPresent(
eventId: 'event_1',
isAppActive: false,
);
final activeDecision = coordinator.shouldPresent(
eventId: 'event_1',
isAppActive: true,
);
expect(hiddenDecision, isFalse);
expect(activeDecision, isTrue);
});
test('suppresses duplicate foreground presentation inside dedupe window', () {
var fakeNow = DateTime(2026, 3, 19, 10, 0, 0);
final coordinator = ReminderPresentationCoordinator(
dedupeWindow: const Duration(seconds: 30),
now: () => fakeNow,
);
final first = coordinator.shouldPresent(
eventId: 'event_42',
isAppActive: true,
);
fakeNow = fakeNow.add(const Duration(seconds: 10));
final second = coordinator.shouldPresent(
eventId: 'event_42',
isAppActive: true,
);
expect(first, isTrue);
expect(second, isFalse);
});
test('allows same event again after dedupe window expires', () {
var fakeNow = DateTime(2026, 3, 19, 10, 0, 0);
final coordinator = ReminderPresentationCoordinator(
dedupeWindow: const Duration(seconds: 30),
now: () => fakeNow,
);
expect(
coordinator.shouldPresent(eventId: 'event_42', isAppActive: true),
isTrue,
);
fakeNow = fakeNow.add(const Duration(seconds: 31));
expect(
coordinator.shouldPresent(eventId: 'event_42', isAppActive: true),
isTrue,
);
});
}
@@ -0,0 +1,36 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:social_app/features/home/ui/controllers/home_keyboard_inset_calculator.dart';
void main() {
test('subtracts bottom safe area from keyboard inset', () {
final inset = HomeKeyboardInsetCalculator.compute(
rawViewInsetBottom: 336,
bottomViewPadding: 34,
);
expect(inset, 302);
});
test('returns zero when keyboard is effectively hidden', () {
final inset = HomeKeyboardInsetCalculator.compute(
rawViewInsetBottom: 6,
bottomViewPadding: 34,
);
expect(inset, 0);
});
test('follows keyboard fallback immediately when inset decreases', () {
final openedInset = HomeKeyboardInsetCalculator.compute(
rawViewInsetBottom: 336,
bottomViewPadding: 34,
);
final collapsedInset = HomeKeyboardInsetCalculator.compute(
rawViewInsetBottom: 120,
bottomViewPadding: 34,
);
expect(openedInset, 302);
expect(collapsedInset, 86);
});
}
@@ -0,0 +1,70 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:social_app/features/settings/data/services/settings_user_cache.dart';
import 'package:social_app/features/users/data/models/user_response.dart';
void main() {
test('getOrLoad calls loader only once when cache exists', () async {
final cache = SettingsUserCache();
var loadCalls = 0;
Future<UserResponse> loader() async {
loadCalls += 1;
return const UserResponse(id: 'u1', username: 'first');
}
final first = await cache.getOrLoad(loader);
final second = await cache.getOrLoad(loader);
expect(first.username, 'first');
expect(second.username, 'first');
expect(loadCalls, 1);
});
test('invalidate forces next load', () async {
final cache = SettingsUserCache();
var loadCalls = 0;
Future<UserResponse> loader() async {
loadCalls += 1;
return UserResponse(id: 'u$loadCalls', username: 'user$loadCalls');
}
final first = await cache.getOrLoad(loader);
cache.invalidate();
final second = await cache.getOrLoad(loader);
expect(first.id, 'u1');
expect(second.id, 'u2');
expect(loadCalls, 2);
});
test(
'invalidate blocks stale inflight response from repopulating cache',
() async {
final cache = SettingsUserCache();
final completer = Completer<UserResponse>();
var loadCalls = 0;
Future<UserResponse> slowLoader() {
loadCalls += 1;
return completer.future;
}
final pending = cache.getOrLoad(slowLoader);
cache.invalidate();
completer.complete(const UserResponse(id: 'u1', username: 'stale'));
await pending;
final fresh = await cache.getOrLoad(() async {
loadCalls += 1;
return const UserResponse(id: 'u2', username: 'fresh');
});
expect(fresh.id, 'u2');
expect(cache.cachedUser?.id, 'u2');
expect(loadCalls, 2);
},
);
}
@@ -0,0 +1,130 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:social_app/core/api/i_api_client.dart';
import 'package:social_app/core/di/injection.dart';
import 'package:social_app/features/friends/data/friends_api.dart';
import 'package:social_app/features/settings/data/services/settings_user_cache.dart';
import 'package:social_app/features/settings/ui/screens/settings_screen.dart';
import 'package:social_app/features/users/data/models/user_response.dart';
import 'package:social_app/features/users/data/users_api.dart';
class _TestApiClient implements IApiClient {
@override
Future<Response<T>> delete<T>(String path, {data, Options? options}) async {
return Response<T>(requestOptions: RequestOptions(path: path));
}
@override
Future<Response<T>> get<T>(String path, {Options? options}) async {
return Response<T>(requestOptions: RequestOptions(path: path));
}
@override
Future<Stream<String>> getSseLines(
String path, {
Map<String, String>? headers,
}) async {
return const Stream<String>.empty();
}
@override
Future<Response<T>> patch<T>(String path, {data, Options? options}) async {
return Response<T>(requestOptions: RequestOptions(path: path));
}
@override
Future<Response<T>> post<T>(String path, {data, Options? options}) async {
return Response<T>(requestOptions: RequestOptions(path: path));
}
}
class _FakeUsersApi extends UsersApi {
_FakeUsersApi(super.client);
int getMeCalls = 0;
@override
Future<UserResponse> getMe() async {
getMeCalls += 1;
return const UserResponse(
id: 'u1',
username: 'Linksy',
phone: '13800000000',
);
}
}
class _FakeFriendsApi extends FriendsApi {
_FakeFriendsApi(super.client);
@override
Future<List<FriendResponse>> getFriends() async {
return const [];
}
}
void main() {
late _FakeUsersApi usersApi;
setUp(() {
final apiClient = _TestApiClient();
if (sl.isRegistered<UsersApi>()) {
sl.unregister<UsersApi>();
}
if (sl.isRegistered<FriendsApi>()) {
sl.unregister<FriendsApi>();
}
if (sl.isRegistered<SettingsUserCache>()) {
sl.unregister<SettingsUserCache>();
}
usersApi = _FakeUsersApi(apiClient);
sl.registerSingleton<UsersApi>(usersApi);
sl.registerSingleton<FriendsApi>(_FakeFriendsApi(apiClient));
sl.registerSingleton<SettingsUserCache>(SettingsUserCache());
});
tearDown(() async {
if (sl.isRegistered<UsersApi>()) {
await sl.unregister<UsersApi>();
}
if (sl.isRegistered<FriendsApi>()) {
await sl.unregister<FriendsApi>();
}
if (sl.isRegistered<SettingsUserCache>()) {
await sl.unregister<SettingsUserCache>();
}
});
testWidgets('settings screen removes account row and shows logout button', (
tester,
) async {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await tester.pump();
expect(find.text('我的账户'), findsNothing);
expect(find.text('退出登录'), findsOneWidget);
});
testWidgets('settings profile hero shows edit icon entry', (tester) async {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await tester.pump();
expect(find.byKey(settingsProfileEditButtonKey), findsOneWidget);
});
testWidgets('settings screen re-entry uses cached user', (tester) async {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await tester.pump();
await tester.pump();
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await tester.pump();
await tester.pump();
expect(usersApi.getMeCalls, 1);
});
}
@@ -0,0 +1,135 @@
import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:social_app/features/todo/data/todo_api.dart';
import 'package:social_app/core/api/i_api_client.dart';
class MockApiClient extends Mock implements IApiClient {}
class FakeRequestOptions extends Fake implements RequestOptions {}
void main() {
late TodoApi todoApi;
late MockApiClient mockClient;
setUpAll(() {
registerFallbackValue(FakeRequestOptions());
});
setUp(() {
mockClient = MockApiClient();
todoApi = TodoApi(mockClient);
});
group('TodoApi.updateTodo - cross-quadrant drag', () {
test(
'calls PATCH with priority when moving to different quadrant',
() async {
const todoId = 'todo-123';
const targetPriority = 2;
when(
() => mockClient.patch(any(), data: any(named: 'data')),
).thenAnswer(
(_) async => Response(
requestOptions: RequestOptions(path: '/api/v1/todos/$todoId'),
data: {
'id': todoId,
'owner_id': 'user-1',
'title': 'Test Todo',
'priority': targetPriority,
'status': 'pending',
'created_at': '2024-01-01T00:00:00Z',
'updated_at': '2024-01-01T00:00:00Z',
},
),
);
final result = await todoApi.updateTodo(
todoId,
priority: targetPriority,
);
expect(result.priority, targetPriority);
verify(
() => mockClient.patch(
'/api/v1/todos/$todoId',
data: {'priority': targetPriority},
),
).called(1);
},
);
test('throws when API fails - triggers rollback', () async {
const todoId = 'todo-123';
when(
() => mockClient.patch(any(), data: any(named: 'data')),
).thenThrow(Exception('Network error'));
expect(() => todoApi.updateTodo(todoId, priority: 2), throwsException);
});
});
group('Quadrant priority mapping', () {
test('priority 1 = important urgent (Q1)', () async {
when(() => mockClient.patch(any(), data: any(named: 'data'))).thenAnswer(
(_) async => Response(
requestOptions: RequestOptions(path: '/api/v1/todos/todo-1'),
data: {
'id': 'todo-1',
'owner_id': 'user-1',
'title': 'Q1 Todo',
'priority': 1,
'status': 'pending',
'created_at': '2024-01-01T00:00:00Z',
'updated_at': '2024-01-01T00:00:00Z',
},
),
);
final result = await todoApi.updateTodo('todo-1', priority: 1);
expect(result.priority, 1);
});
test('priority 2 = important not urgent (Q3)', () async {
when(() => mockClient.patch(any(), data: any(named: 'data'))).thenAnswer(
(_) async => Response(
requestOptions: RequestOptions(path: '/api/v1/todos/todo-2'),
data: {
'id': 'todo-2',
'owner_id': 'user-1',
'title': 'Q3 Todo',
'priority': 2,
'status': 'pending',
'created_at': '2024-01-01T00:00:00Z',
'updated_at': '2024-01-01T00:00:00Z',
},
),
);
final result = await todoApi.updateTodo('todo-2', priority: 2);
expect(result.priority, 2);
});
test('priority 3 = urgent not important (Q2)', () async {
when(() => mockClient.patch(any(), data: any(named: 'data'))).thenAnswer(
(_) async => Response(
requestOptions: RequestOptions(path: '/api/v1/todos/todo-3'),
data: {
'id': 'todo-3',
'owner_id': 'user-1',
'title': 'Q2 Todo',
'priority': 3,
'status': 'pending',
'created_at': '2024-01-01T00:00:00Z',
'updated_at': '2024-01-01T00:00:00Z',
},
),
);
final result = await todoApi.updateTodo('todo-3', priority: 3);
expect(result.priority, 3);
});
});
}
@@ -0,0 +1,20 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('AndroidManifest declares ActionBroadcastReceiver', () {
final manifestFile = File('android/app/src/main/AndroidManifest.xml');
expect(manifestFile.existsSync(), isTrue);
final manifestContent = manifestFile.readAsStringSync();
expect(
manifestContent,
contains(
'com.dexterous.flutterlocalnotifications.ActionBroadcastReceiver',
),
);
});
}
@@ -0,0 +1,22 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('AppDelegate registers flutter local notifications callback', () {
final appDelegateFile = File('ios/Runner/AppDelegate.swift');
expect(appDelegateFile.existsSync(), isTrue);
final appDelegateContent = appDelegateFile.readAsStringSync();
expect(
appDelegateContent,
contains('FlutterLocalNotificationsPlugin.setPluginRegistrantCallback'),
);
expect(
appDelegateContent,
contains('GeneratedPluginRegistrant.register(with: registry)'),
);
});
}