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
@@ -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,
),
),
);
}
}