积分、成就系统

This commit is contained in:
ytc1012
2025-11-27 13:37:10 +08:00
parent 0195cdf54b
commit 58f6ec39b7
35 changed files with 7786 additions and 199 deletions

View File

@@ -4,6 +4,7 @@ import '../theme/app_colors.dart';
import '../theme/app_text_styles.dart';
import '../services/storage_service.dart';
import '../services/encouragement_service.dart';
import '../models/achievement_config.dart';
import 'home_screen.dart';
import 'history_screen.dart';
@@ -11,12 +12,22 @@ import 'history_screen.dart';
class CompleteScreen extends StatelessWidget {
final int focusedMinutes;
final int distractionCount;
final int pointsEarned;
final int basePoints;
final int honestyBonus;
final int totalPoints;
final List<String> newAchievements;
final EncouragementService encouragementService;
const CompleteScreen({
super.key,
required this.focusedMinutes,
required this.distractionCount,
required this.pointsEarned,
required this.basePoints,
required this.honestyBonus,
required this.totalPoints,
this.newAchievements = const [],
required this.encouragementService,
});
@@ -33,99 +44,413 @@ class CompleteScreen extends StatelessWidget {
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Success Icon
const Text(
'',
style: TextStyle(fontSize: 64),
),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 40),
const SizedBox(height: 32),
// You focused for X minutes
Text(
l10n.youFocusedFor,
style: AppTextStyles.headline,
),
const SizedBox(height: 8),
Text(
l10n.minutesValue(focusedMinutes, l10n.minutes(focusedMinutes)),
style: AppTextStyles.largeNumber,
),
const SizedBox(height: 40),
// Stats Card
Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(16),
// Success Icon
const Text(
'',
style: TextStyle(fontSize: 64),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.totalToday(todayTotal),
style: AppTextStyles.bodyText,
),
const SizedBox(height: 12),
Text(
l10n.distractionsCount(todayDistractions, l10n.times(todayDistractions)),
style: AppTextStyles.bodyText,
),
const SizedBox(height: 20),
Text(
'"$encouragement"',
style: AppTextStyles.encouragementQuote,
),
],
const SizedBox(height: 32),
// You focused for X minutes
Text(
l10n.youFocusedFor,
style: AppTextStyles.headline,
),
const SizedBox(height: 8),
Text(
l10n.minutesValue(focusedMinutes, l10n.minutes(focusedMinutes)),
style: AppTextStyles.largeNumber,
),
),
const SizedBox(height: 40),
const SizedBox(height: 32),
// Start Another Button
SizedBox(
width: double.infinity,
child: ElevatedButton(
// Points Earned Section
_buildPointsCard(context, l10n),
const SizedBox(height: 16),
// Achievement Unlocked (if any)
if (newAchievements.isNotEmpty)
..._buildAchievementCards(context, l10n),
const SizedBox(height: 16),
// Stats Card
Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.totalToday(todayTotal),
style: AppTextStyles.bodyText,
),
const SizedBox(height: 12),
Text(
l10n.distractionsCount(todayDistractions, l10n.times(todayDistractions)),
style: AppTextStyles.bodyText,
),
const SizedBox(height: 20),
Text(
'"$encouragement"',
style: AppTextStyles.encouragementQuote,
),
],
),
),
const SizedBox(height: 24),
// Total Points Display
Text(
l10n.totalPoints(totalPoints),
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
fontWeight: FontWeight.w600,
color: AppColors.primary,
),
),
const SizedBox(height: 24),
// Start Another Button
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => HomeScreen(
encouragementService: encouragementService,
),
),
(route) => false,
);
},
child: Text(l10n.startAnother),
),
),
const SizedBox(height: 16),
// View Full Report - Navigate to History
TextButton(
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => HomeScreen(
encouragementService: encouragementService,
),
builder: (context) => const HistoryScreen(),
),
(route) => false,
(route) => route.isFirst,
);
},
child: Text(l10n.startAnother),
child: Text(l10n.viewHistory),
),
),
const SizedBox(height: 16),
// View Full Report - Navigate to History
TextButton(
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => const HistoryScreen(),
),
(route) => route.isFirst, // Keep only the home screen in stack
);
},
child: Text(l10n.viewHistory),
),
],
const SizedBox(height: 40),
],
),
),
),
),
);
}
/// Build points earned card
Widget _buildPointsCard(BuildContext context, AppLocalizations l10n) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: AppColors.primary.withValues(alpha: 0.3),
width: 2,
),
),
child: Column(
children: [
// Main points display
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
l10n.earnedPoints,
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 18,
color: AppColors.textSecondary,
),
),
const SizedBox(width: 8),
Text(
'+$pointsEarned',
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 28,
fontWeight: FontWeight.bold,
color: AppColors.primary,
),
),
const Text(
'',
style: TextStyle(fontSize: 24),
),
],
),
const SizedBox(height: 16),
Divider(thickness: 1, color: AppColors.textSecondary.withValues(alpha: 0.2)),
const SizedBox(height: 12),
// Points breakdown
_buildPointRow(
l10n.basePoints,
'+$basePoints',
AppColors.success,
),
if (honestyBonus > 0) ...[
const SizedBox(height: 8),
_buildPointRow(
l10n.honestyBonus,
'+$honestyBonus',
AppColors.success,
subtitle: l10n.distractionsRecorded(distractionCount, l10n.distractions(distractionCount)),
),
],
],
),
);
}
/// Build a single point row in the breakdown
Widget _buildPointRow(
String label,
String points,
Color color, {
String? subtitle,
}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Column(
children: [
Row(
children: [
Text(
'├─ ',
style: TextStyle(
color: AppColors.textSecondary.withValues(alpha: 0.4),
fontFamily: 'Nunito',
),
),
Text(
label,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
color: AppColors.textSecondary,
),
),
const Spacer(),
Text(
points,
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
fontWeight: FontWeight.w600,
color: color,
),
),
],
),
if (subtitle != null)
Padding(
padding: const EdgeInsets.only(left: 24, top: 4),
child: Row(
children: [
Text(
subtitle,
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 12,
color: AppColors.textSecondary.withValues(alpha: 0.7),
),
),
],
),
),
],
),
);
}
/// Build achievement unlocked cards
List<Widget> _buildAchievementCards(BuildContext context, AppLocalizations l10n) {
return newAchievements.map((achievementId) {
final achievement = AchievementConfig.getById(achievementId);
if (achievement == null) return const SizedBox.shrink();
return Container(
margin: const EdgeInsets.only(bottom: 16),
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFFFFD700), Color(0xFFFFC107)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.orange.withValues(alpha: 0.4),
blurRadius: 20,
offset: const Offset(0, 8),
),
],
),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
achievement.icon,
style: const TextStyle(fontSize: 32),
),
const SizedBox(width: 12),
Text(
l10n.achievementUnlocked,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
],
),
const SizedBox(height: 12),
Text(
_getLocalizedAchievementName(l10n, achievement.nameKey),
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
const SizedBox(height: 4),
Text(
_getLocalizedAchievementDesc(l10n, achievement.descKey),
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
color: Colors.white,
),
textAlign: TextAlign.center,
),
if (achievement.bonusPoints > 0) ...[
const SizedBox(height: 8),
Text(
l10n.bonusPoints(achievement.bonusPoints),
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
fontWeight: FontWeight.w600,
color: Colors.white,
),
),
],
],
),
);
}).toList();
}
/// Get localized achievement name by key
String _getLocalizedAchievementName(AppLocalizations l10n, String key) {
switch (key) {
case 'achievement_first_session_name':
return l10n.achievement_first_session_name;
case 'achievement_sessions_10_name':
return l10n.achievement_sessions_10_name;
case 'achievement_sessions_50_name':
return l10n.achievement_sessions_50_name;
case 'achievement_sessions_100_name':
return l10n.achievement_sessions_100_name;
case 'achievement_honest_bronze_name':
return l10n.achievement_honest_bronze_name;
case 'achievement_honest_silver_name':
return l10n.achievement_honest_silver_name;
case 'achievement_honest_gold_name':
return l10n.achievement_honest_gold_name;
case 'achievement_marathon_name':
return l10n.achievement_marathon_name;
case 'achievement_century_name':
return l10n.achievement_century_name;
case 'achievement_master_name':
return l10n.achievement_master_name;
case 'achievement_persistence_star_name':
return l10n.achievement_persistence_star_name;
case 'achievement_monthly_habit_name':
return l10n.achievement_monthly_habit_name;
case 'achievement_centurion_name':
return l10n.achievement_centurion_name;
case 'achievement_year_warrior_name':
return l10n.achievement_year_warrior_name;
default:
return key;
}
}
/// Get localized achievement description by key
String _getLocalizedAchievementDesc(AppLocalizations l10n, String key) {
switch (key) {
case 'achievement_first_session_desc':
return l10n.achievement_first_session_desc;
case 'achievement_sessions_10_desc':
return l10n.achievement_sessions_10_desc;
case 'achievement_sessions_50_desc':
return l10n.achievement_sessions_50_desc;
case 'achievement_sessions_100_desc':
return l10n.achievement_sessions_100_desc;
case 'achievement_honest_bronze_desc':
return l10n.achievement_honest_bronze_desc;
case 'achievement_honest_silver_desc':
return l10n.achievement_honest_silver_desc;
case 'achievement_honest_gold_desc':
return l10n.achievement_honest_gold_desc;
case 'achievement_marathon_desc':
return l10n.achievement_marathon_desc;
case 'achievement_century_desc':
return l10n.achievement_century_desc;
case 'achievement_master_desc':
return l10n.achievement_master_desc;
case 'achievement_persistence_star_desc':
return l10n.achievement_persistence_star_desc;
case 'achievement_monthly_habit_desc':
return l10n.achievement_monthly_habit_desc;
case 'achievement_centurion_desc':
return l10n.achievement_centurion_desc;
case 'achievement_year_warrior_desc':
return l10n.achievement_year_warrior_desc;
default:
return key;
}
}
}

View File

@@ -9,6 +9,8 @@ import '../services/di.dart';
import '../services/storage_service.dart';
import '../services/encouragement_service.dart';
import '../services/notification_service.dart';
import '../services/points_service.dart';
import '../services/achievement_service.dart';
import '../components/timer_display.dart';
import '../components/distraction_button.dart';
import '../components/control_buttons.dart';
@@ -38,6 +40,8 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
bool _isInBackground = false;
final NotificationService _notificationService = getIt<NotificationService>();
final StorageService _storageService = getIt<StorageService>();
final PointsService _pointsService = getIt<PointsService>();
final AchievementService _achievementService = getIt<AchievementService>();
@override
void initState() {
@@ -85,7 +89,8 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
final l10n = AppLocalizations.of(context)!;
final minutes = _remainingSeconds ~/ 60;
final seconds = _remainingSeconds % 60;
final timeStr = '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
final timeStr =
'${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
_notificationService.showOngoingFocusNotification(
remainingMinutes: minutes,
remainingSeconds: seconds,
@@ -107,7 +112,8 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
final l10n = AppLocalizations.of(context)!;
final minutes = _remainingSeconds ~/ 60;
final seconds = _remainingSeconds % 60;
final timeStr = '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
final timeStr =
'${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
_notificationService.updateOngoingFocusNotification(
remainingMinutes: minutes,
remainingSeconds: seconds,
@@ -130,7 +136,8 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
// Cancel ongoing notification and show completion notification
await _notificationService.cancelOngoingFocusNotification();
await _saveFocusSession(completed: true);
// Calculate points and update user progress
final pointsData = await _saveFocusSession(completed: true);
if (!mounted) return;
@@ -162,6 +169,11 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
builder: (context) => CompleteScreen(
focusedMinutes: widget.durationMinutes,
distractionCount: _distractions.length,
pointsEarned: pointsData['pointsEarned']!,
basePoints: pointsData['basePoints']!,
honestyBonus: pointsData['honestyBonus']!,
totalPoints: pointsData['totalPoints']!,
newAchievements: pointsData['newAchievements'] as List<String>,
encouragementService: widget.encouragementService,
),
),
@@ -183,8 +195,11 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
void _stopEarly() {
final l10n = AppLocalizations.of(context)!;
final actualMinutes = ((widget.durationMinutes * 60 - _remainingSeconds) / 60).floor();
final minuteText = actualMinutes == 1 ? l10n.minutes(1) : l10n.minutes(actualMinutes);
final actualMinutes =
((widget.durationMinutes * 60 - _remainingSeconds) / 60).floor();
final minuteText = actualMinutes == 1
? l10n.minutes(1)
: l10n.minutes(actualMinutes);
showDialog(
context: context,
@@ -200,21 +215,36 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
child: Text(l10n.keepGoing),
),
TextButton(
onPressed: () {
Navigator.pop(context); // Close dialog
onPressed: () async {
// Close dialog immediately
Navigator.pop(context);
_timer.cancel();
_saveFocusSession(completed: false);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => CompleteScreen(
focusedMinutes: actualMinutes,
distractionCount: _distractions.length,
encouragementService: widget.encouragementService,
),
),
);
// Calculate points and update user progress
final pointsData = await _saveFocusSession(completed: false);
// Create a new context for navigation
if (mounted) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => CompleteScreen(
focusedMinutes: actualMinutes,
distractionCount: _distractions.length,
pointsEarned: pointsData['pointsEarned']!,
basePoints: pointsData['basePoints']!,
honestyBonus: pointsData['honestyBonus']!,
totalPoints: pointsData['totalPoints']!,
newAchievements: pointsData['newAchievements'] as List<String>,
encouragementService: widget.encouragementService,
),
),
);
}
});
}
},
child: Text(l10n.yesStop),
),
@@ -223,7 +253,9 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
);
}
Future<void> _saveFocusSession({required bool completed}) async {
Future<Map<String, dynamic>> _saveFocusSession({
required bool completed,
}) async {
try {
final actualMinutes = completed
? widget.durationMinutes
@@ -238,9 +270,47 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
distractionTypes: _distractions,
);
// Save session
await _storageService.saveFocusSession(session);
// Calculate points
final pointsBreakdown = _pointsService.calculateSessionPoints(session);
// Update user progress
final progress = _storageService.getUserProgress();
// Add points (convert to int explicitly)
progress.totalPoints += (pointsBreakdown['total']! as num).toInt();
progress.currentPoints += (pointsBreakdown['total']! as num).toInt();
// Update statistics
progress.totalSessions += 1;
progress.totalFocusMinutes += actualMinutes;
progress.totalDistractions += _distractions.length;
final newAchievements = await _achievementService.checkAchievementsAsync(
progress,
);
// Save updated progress
await _storageService.saveUserProgress(progress);
return {
'pointsEarned': pointsBreakdown['total']!,
'basePoints': pointsBreakdown['basePoints']!,
'honestyBonus': pointsBreakdown['honestyBonus']!,
'totalPoints': progress.totalPoints,
'newAchievements': newAchievements,
};
} catch (e) {
// Ignore save errors silently
// Return default values on error
return {
'pointsEarned': 0,
'basePoints': 0,
'honestyBonus': 0,
'totalPoints': 0,
'newAchievements': <String>[],
};
}
}
@@ -249,7 +319,10 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
// Map distraction types to translations
final distractionOptions = [
(type: DistractionType.phoneNotification, label: l10n.distractionPhoneNotification),
(
type: DistractionType.phoneNotification,
label: l10n.distractionPhoneNotification,
),
(type: DistractionType.socialMedia, label: l10n.distractionSocialMedia),
(type: DistractionType.thoughts, label: l10n.distractionThoughts),
(type: DistractionType.other, label: l10n.distractionOther),
@@ -356,7 +429,11 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
// Show distraction-specific encouragement toast
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(widget.encouragementService.getRandomMessage(EncouragementType.distraction)),
content: Text(
widget.encouragementService.getRandomMessage(
EncouragementType.distraction,
),
),
duration: const Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
),
@@ -377,9 +454,8 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
padding: const EdgeInsets.all(24.0),
child: Column(
children: [
SizedBox(
height: MediaQuery.of(context).size.height * 0.2,
),
SizedBox(height: MediaQuery.of(context).size.height * 0.2),
SizedBox(height: MediaQuery.of(context).size.height * 0.2),
// Timer Display Component
TimerDisplay(remainingSeconds: _remainingSeconds),
@@ -403,10 +479,8 @@ class _FocusScreenState extends State<FocusScreen> with WidgetsBindingObserver {
resumeText: l10n.resume,
stopText: l10n.stopSession,
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.2,
),
SizedBox(height: MediaQuery.of(context).size.height * 0.2),
SizedBox(height: MediaQuery.of(context).size.height * 0.2),
],
),
),

View File

@@ -1,10 +1,11 @@
import 'package:flutter/material.dart';
import '../l10n/app_localizations.dart';
import '../theme/app_colors.dart';
import '../theme/app_text_styles.dart';
import '../models/focus_session.dart';
import '../services/storage_service.dart';
import 'package:intl/intl.dart';
import '../l10n/app_localizations.dart';
import 'session_detail_screen.dart';
/// History Screen - Shows past focus sessions
class HistoryScreen extends StatefulWidget {
@@ -81,10 +82,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'📊',
style: TextStyle(fontSize: 64),
),
const Text('📊', style: TextStyle(fontSize: 64)),
const SizedBox(height: 24),
Text(
l10n.noFocusSessionsYet,
@@ -108,7 +106,12 @@ class _HistoryScreenState extends State<HistoryScreen> {
);
}
Widget _buildTodaySummary(AppLocalizations l10n, int totalMins, int distractions, int sessions) {
Widget _buildTodaySummary(
AppLocalizations l10n,
int totalMins,
int distractions,
int sessions,
) {
return Container(
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
@@ -155,13 +158,20 @@ class _HistoryScreenState extends State<HistoryScreen> {
Row(
children: [
Expanded(
child: _buildStat('Total', l10n.minutesValue(totalMins, l10n.minutes(totalMins)), '⏱️'),
child: _buildStat(
'Total',
l10n.minutesValue(totalMins, l10n.minutes(totalMins)),
'⏱️',
),
),
const SizedBox(width: 16),
Expanded(
child: _buildStat(
'Distractions',
l10n.distractionsCount(distractions, l10n.times(distractions)),
l10n.distractionsCount(
distractions,
l10n.times(distractions),
),
'🤚',
),
),
@@ -176,10 +186,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
emoji,
style: const TextStyle(fontSize: 24),
),
Text(emoji, style: const TextStyle(fontSize: 24)),
const SizedBox(height: 8),
Text(
label,
@@ -204,7 +211,11 @@ class _HistoryScreenState extends State<HistoryScreen> {
);
}
Widget _buildDateSection(AppLocalizations l10n, DateTime date, List<FocusSession> sessions) {
Widget _buildDateSection(
AppLocalizations l10n,
DateTime date,
List<FocusSession> sessions,
) {
final isToday = _isToday(date);
final dateLabel = isToday
? l10n.today
@@ -257,83 +268,108 @@ class _HistoryScreenState extends State<HistoryScreen> {
final statusEmoji = session.completed ? '' : '⏸️';
final statusText = session.completed ? l10n.completed : l10n.stoppedEarly;
return Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: AppColors.divider,
width: 1,
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SessionDetailScreen(session: session),
),
);
},
child: Container(
margin: const EdgeInsets.only(bottom: 12),
color: Colors.black.withValues(alpha: 0.05),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: AppColors.divider, width: 1),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
),
child: Row(
children: [
// Time
Text(
timeStr,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
),
),
const SizedBox(width: 16),
// Duration
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.minutesValue(session.actualMinutes, l10n.minutes(session.actualMinutes)),
style: AppTextStyles.bodyText,
),
if (session.distractionCount > 0)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
l10n.distractionsCount(session.distractionCount, l10n.times(session.distractionCount)),
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
fontWeight: FontWeight.w400,
color: AppColors.textSecondary,
),
),
),
],
),
),
// Status badge
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
decoration: BoxDecoration(
color: session.completed
? AppColors.success.withValues(alpha: 0.1)
: AppColors.distractionButton,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'$statusEmoji $statusText',
style: TextStyle(
child: Row(
children: [
// Time
Text(
timeStr,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 12,
fontSize: 16,
fontWeight: FontWeight.w600,
color: session.completed
? AppColors.success
: AppColors.textSecondary,
color: AppColors.textPrimary,
),
),
),
],
const SizedBox(width: 16),
// Duration
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.minutesValue(
session.actualMinutes,
l10n.minutes(session.actualMinutes),
),
style: AppTextStyles.bodyText,
),
if (session.distractionCount > 0)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
l10n.distractionsCount(
session.distractionCount,
l10n.times(session.distractionCount),
),
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
fontWeight: FontWeight.w400,
color: AppColors.textSecondary,
),
),
),
],
),
),
// Status badge
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: session.completed
? AppColors.success.withValues(alpha: 0.1)
: AppColors.distractionButton,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'$statusEmoji $statusText',
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 12,
fontWeight: FontWeight.w600,
color: session.completed
? AppColors.success
: AppColors.textSecondary,
),
),
),
// Arrow indicator
const SizedBox(width: 8),
const Icon(
Icons.arrow_forward_ios,
size: 12,
color: AppColors.textSecondary,
),
],
),
),
);
}

View File

@@ -3,9 +3,12 @@ import '../l10n/app_localizations.dart';
import '../theme/app_colors.dart';
import '../theme/app_text_styles.dart';
import '../services/encouragement_service.dart';
import '../services/storage_service.dart';
import '../services/di.dart';
import 'focus_screen.dart';
import 'history_screen.dart';
import 'settings_screen.dart';
import 'profile_screen.dart';
/// Home Screen - Loads default duration from settings
class HomeScreen extends StatefulWidget {
@@ -22,6 +25,7 @@ class HomeScreen extends StatefulWidget {
class _HomeScreenState extends State<HomeScreen> {
int _defaultDuration = 25;
final StorageService _storageService = getIt<StorageService>();
@override
void initState() {
@@ -46,6 +50,7 @@ class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final progress = _storageService.getUserProgress();
return Scaffold(
backgroundColor: AppColors.background,
@@ -53,8 +58,12 @@ class _HomeScreenState extends State<HomeScreen> {
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Points Card at the top
_buildPointsCard(context, progress),
const SizedBox(height: 32),
// App Title
Text(
l10n.appTitle,
@@ -100,9 +109,10 @@ class _HomeScreenState extends State<HomeScreen> {
),
),
);
// Reload duration when returning
// Reload duration and refresh points when returning
if (result == true || mounted) {
_loadDefaultDuration();
setState(() {}); // Refresh to show updated points
}
},
child: Row(
@@ -168,4 +178,156 @@ class _HomeScreenState extends State<HomeScreen> {
),
);
}
/// Build points card widget
Widget _buildPointsCard(BuildContext context, progress) {
final l10n = AppLocalizations.of(context)!;
return GestureDetector(
onTap: () async {
// Navigate to ProfileScreen
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ProfileScreen(),
),
);
// Refresh points when returning from ProfileScreen
setState(() {});
},
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
AppColors.primary.withValues(alpha: 0.1),
AppColors.primary.withValues(alpha: 0.05),
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: AppColors.primary.withValues(alpha: 0.2),
width: 1,
),
),
child: Row(
children: [
// Left side: Points and Level
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
// Points
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Text(
'',
style: TextStyle(fontSize: 20),
),
const SizedBox(width: 4),
Text(
'${progress.totalPoints}',
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 24,
fontWeight: FontWeight.bold,
color: AppColors.primary,
),
),
],
),
Text(
l10n.points,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 12,
color: AppColors.textSecondary,
),
),
],
),
// Level
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Text(
'🎖️',
style: TextStyle(fontSize: 20),
),
const SizedBox(width: 4),
Text(
'Lv ${progress.level}',
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 24,
fontWeight: FontWeight.bold,
color: AppColors.primary,
),
),
],
),
Text(
l10n.level,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 12,
color: AppColors.textSecondary,
),
),
],
),
],
),
),
// Right side: Check-in status
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: progress.hasCheckedInToday
? AppColors.success.withValues(alpha: 0.1)
: AppColors.white.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(12),
),
child: Column(
children: [
Text(
progress.hasCheckedInToday ? '' : '📅',
style: const TextStyle(fontSize: 20),
),
const SizedBox(height: 4),
Text(
progress.hasCheckedInToday ? l10n.checked : l10n.checkIn,
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 10,
color: progress.hasCheckedInToday
? AppColors.success
: AppColors.textSecondary,
fontWeight: FontWeight.w600,
),
),
if (progress.consecutiveCheckIns > 0)
Text(
'🔥 ${progress.consecutiveCheckIns}',
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 12,
fontWeight: FontWeight.bold,
color: AppColors.primary,
),
),
],
),
),
],
),
),
);
}
}

View File

@@ -0,0 +1,821 @@
import 'package:flutter/material.dart';
import '../l10n/app_localizations.dart';
import '../theme/app_colors.dart';
import '../services/storage_service.dart';
import '../services/points_service.dart';
import '../services/achievement_service.dart';
import '../services/di.dart';
import '../models/user_progress.dart';
import '../models/achievement_config.dart';
/// Profile Screen - Shows user points, level, check-in calendar, and achievements
class ProfileScreen extends StatefulWidget {
const ProfileScreen({super.key});
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
final StorageService _storageService = getIt<StorageService>();
final PointsService _pointsService = getIt<PointsService>();
final AchievementService _achievementService = getIt<AchievementService>();
late UserProgress _progress;
@override
void initState() {
super.initState();
_progress = _storageService.getUserProgress();
}
Future<void> _handleCheckIn() async {
final l10n = AppLocalizations.of(context)!;
if (_progress.hasCheckedInToday) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(l10n.alreadyCheckedIn),
duration: const Duration(seconds: 2),
),
);
return;
}
// Process check-in with detailed breakdown
final checkInResult = _pointsService.processCheckIn(_progress);
final pointsEarned = checkInResult['points'] as int;
// Add points
_progress.totalPoints += pointsEarned;
_progress.currentPoints += pointsEarned;
// Check for newly unlocked achievements (streak achievements) asynchronously
final newAchievements = await _achievementService.checkAchievementsAsync(
_progress,
);
// Save progress
await _storageService.saveUserProgress(_progress);
// Update UI
setState(() {});
// Show success message
if (!mounted) return;
String message = l10n.checkInSuccess(pointsEarned);
if (_progress.consecutiveCheckIns % 7 == 0) {
message += '\n${l10n.weeklyStreakBonus}';
}
if (newAchievements.isNotEmpty) {
message += '\n${l10n.newAchievementUnlocked}';
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
duration: const Duration(seconds: 3),
backgroundColor: AppColors.success,
),
);
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
title: Text(
l10n.profile,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 20,
fontWeight: FontWeight.bold,
color: AppColors.textPrimary,
),
),
centerTitle: true,
),
body: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
// User header card
_buildUserHeaderCard(l10n),
const SizedBox(height: 24),
// Check-in calendar
_buildCheckInCalendar(l10n),
const SizedBox(height: 24),
// Achievement wall
_buildAchievementWall(l10n),
const SizedBox(height: 24),
],
),
),
),
);
}
/// Build user header card with points, level, and progress bar
Widget _buildUserHeaderCard(AppLocalizations l10n) {
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [AppColors.primary, AppColors.primary.withValues(alpha: 0.8)],
),
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: AppColors.primary.withValues(alpha: 0.3),
blurRadius: 12,
offset: const Offset(0, 4),
),
],
),
child: Column(
children: [
// User icon (placeholder)
const CircleAvatar(
radius: 40,
backgroundColor: Colors.white,
child: Text('👤', style: TextStyle(fontSize: 40)),
),
const SizedBox(height: 16),
// User name (placeholder)
Text(
l10n.focuser,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
const SizedBox(height: 20),
// Points and Level row
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
// Points
Column(
children: [
Row(
children: [
const Text('', style: TextStyle(fontSize: 28)),
const SizedBox(width: 4),
Text(
'${_progress.totalPoints}',
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 28,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
],
),
Text(
l10n.points,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
color: Colors.white,
),
),
],
),
// Divider
Container(
height: 40,
width: 1,
color: Colors.white.withValues(alpha: 0.3),
),
// Level
Column(
children: [
Container(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(16),
),
child: Row(
children: [
const Text('🎖️', style: TextStyle(fontSize: 24)),
const SizedBox(width: 4),
Text(
'Lv ${_progress.level}',
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
],
),
),
const SizedBox(height: 4),
Text(
l10n.level,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
color: Colors.white,
),
),
],
),
],
),
const SizedBox(height: 20),
// Level progress bar
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.pointsToNextLevel(
_progress.pointsToNextLevel,
_progress.level + 1,
),
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 12,
color: Colors.white.withValues(alpha: 0.9),
),
),
const SizedBox(height: 8),
Stack(
children: [
// Background bar
Container(
height: 10,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(5),
),
),
// Progress bar
FractionallySizedBox(
widthFactor: _progress.levelProgress,
child: Container(
height: 10,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
),
),
],
),
const SizedBox(height: 4),
Align(
alignment: Alignment.centerRight,
child: Text(
'${(_progress.levelProgress * 100).toInt()}%',
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 12,
color: Colors.white.withValues(alpha: 0.9),
),
),
),
],
),
],
),
);
}
/// Build check-in calendar section
Widget _buildCheckInCalendar(AppLocalizations l10n) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Header
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
l10n.checkInCalendar,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 18,
fontWeight: FontWeight.bold,
color: AppColors.textPrimary,
),
),
Text(
l10n.daysCount(_progress.checkInHistory.length),
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
color: AppColors.textSecondary,
),
),
],
),
const SizedBox(height: 16),
// Check-in button
if (!_progress.hasCheckedInToday)
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _handleCheckIn,
style: ElevatedButton.styleFrom(
backgroundColor: AppColors.primary,
padding: const EdgeInsets.symmetric(vertical: 12),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
l10n.checkInToday,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
if (_progress.hasCheckedInToday)
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 12),
decoration: BoxDecoration(
color: AppColors.success.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
l10n.checkedInToday,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
fontWeight: FontWeight.w600,
color: AppColors.success,
),
),
],
),
),
const SizedBox(height: 16),
// Stats row
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildStatItem(
l10n.currentStreak,
l10n.daysCount(_progress.consecutiveCheckIns),
),
Container(height: 40, width: 1, color: AppColors.divider),
_buildStatItem(
l10n.longestStreak,
l10n.daysCount(_progress.longestCheckInStreak),
),
],
),
const SizedBox(height: 16),
// Calendar grid (last 28 days)
_buildCalendarGrid(),
],
),
);
}
/// Build calendar grid showing check-in history
Widget _buildCalendarGrid() {
final now = DateTime.now();
final today = DateTime(now.year, now.month, now.day);
return Column(
children: [
// Weekday labels
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: ['S', 'M', 'T', 'W', 'T', 'F', 'S']
.map(
(day) => SizedBox(
width: 40,
child: Center(
child: Text(
day,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 12,
fontWeight: FontWeight.w600,
color: AppColors.textSecondary,
),
),
),
),
)
.toList(),
),
const SizedBox(height: 8),
// Calendar days (last 4 weeks)
Wrap(
spacing: 4,
runSpacing: 4,
children: List.generate(28, (index) {
final date = today.subtract(Duration(days: 27 - index));
final isCheckedIn = _progress.checkInHistory.any(
(checkInDate) =>
checkInDate.year == date.year &&
checkInDate.month == date.month &&
checkInDate.day == date.day,
);
final isToday = date == today;
return Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: isCheckedIn
? AppColors.primary.withValues(alpha: 0.2)
: Colors.transparent,
borderRadius: BorderRadius.circular(8),
border: isToday
? Border.all(color: AppColors.primary, width: 2)
: null,
),
child: Center(
child: Text(
isCheckedIn ? '' : date.day.toString(),
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
fontWeight: FontWeight.w600,
color: isCheckedIn
? AppColors.primary
: AppColors.textSecondary,
),
),
),
);
}),
),
],
);
}
/// Build a stat item
Widget _buildStatItem(String label, String value) {
return Column(
children: [
Text(
value,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 20,
fontWeight: FontWeight.bold,
color: AppColors.primary,
),
),
const SizedBox(height: 4),
Text(
label,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 12,
color: AppColors.textSecondary,
),
textAlign: TextAlign.center,
),
],
);
}
/// Build achievement wall section
Widget _buildAchievementWall(AppLocalizations l10n) {
final allAchievements = AchievementConfig.all;
final unlockedCount = _progress.unlockedAchievements.length;
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Header
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
l10n.achievements,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 18,
fontWeight: FontWeight.bold,
color: AppColors.textPrimary,
),
),
Text(
'$unlockedCount/${allAchievements.length}',
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
color: AppColors.textSecondary,
),
),
],
),
const SizedBox(height: 16),
// Achievement list
...allAchievements.take(6).map((achievement) {
final isUnlocked = _progress.unlockedAchievements.containsKey(
achievement.id,
);
final progress = _achievementService.getAchievementProgress(
_progress,
achievement,
);
final currentValue = _achievementService.getAchievementCurrentValue(
_progress,
achievement,
);
return _buildAchievementItem(
l10n: l10n,
achievement: achievement,
isUnlocked: isUnlocked,
progress: progress,
currentValue: currentValue,
);
}),
const SizedBox(height: 16),
// View all button
Center(
child: TextButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(l10n.allAchievementsComingSoon),
duration: const Duration(seconds: 2),
),
);
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
l10n.viewAllAchievements,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
const SizedBox(width: 4),
const Icon(Icons.arrow_forward, size: 16),
],
),
),
),
],
),
);
}
/// Build a single achievement item
Widget _buildAchievementItem({
required AppLocalizations l10n,
required AchievementConfig achievement,
required bool isUnlocked,
required double progress,
required int currentValue,
}) {
return Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: isUnlocked
? AppColors.success.withValues(alpha: 0.05)
: AppColors.background,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: isUnlocked
? AppColors.success.withValues(alpha: 0.3)
: AppColors.divider,
width: 1,
),
),
child: Row(
children: [
// Icon
Container(
width: 48,
height: 48,
decoration: BoxDecoration(
color: isUnlocked
? AppColors.success.withValues(alpha: 0.1)
: Colors.grey.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
),
child: Center(
child: Text(
achievement.icon,
style: TextStyle(
fontSize: 24,
color: isUnlocked ? null : Colors.grey,
),
),
),
),
const SizedBox(width: 12),
// Content
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_getLocalizedAchievementName(l10n, achievement.nameKey),
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
fontWeight: FontWeight.w600,
color: isUnlocked
? AppColors.textPrimary
: AppColors.textSecondary,
),
),
const SizedBox(height: 4),
Text(
_getLocalizedAchievementDesc(l10n, achievement.descKey),
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 12,
color: AppColors.textSecondary.withValues(alpha: 0.8),
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (!isUnlocked) ...[
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: LinearProgressIndicator(
value: progress,
backgroundColor: Colors.grey.withValues(alpha: 0.2),
valueColor: const AlwaysStoppedAnimation(
AppColors.primary,
),
),
),
const SizedBox(width: 8),
Text(
'$currentValue/${achievement.requiredValue}',
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 10,
color: AppColors.textSecondary,
),
),
],
),
],
],
),
),
const SizedBox(width: 8),
// Status icon
if (isUnlocked)
const Icon(Icons.check_circle, color: AppColors.success, size: 24)
else
const Icon(
Icons.lock_outline,
color: AppColors.textSecondary,
size: 24,
),
],
),
);
}
/// Get localized achievement name by key
String _getLocalizedAchievementName(AppLocalizations l10n, String key) {
switch (key) {
case 'achievement_first_session_name':
return l10n.achievement_first_session_name;
case 'achievement_sessions_10_name':
return l10n.achievement_sessions_10_name;
case 'achievement_sessions_50_name':
return l10n.achievement_sessions_50_name;
case 'achievement_sessions_100_name':
return l10n.achievement_sessions_100_name;
case 'achievement_honest_bronze_name':
return l10n.achievement_honest_bronze_name;
case 'achievement_honest_silver_name':
return l10n.achievement_honest_silver_name;
case 'achievement_honest_gold_name':
return l10n.achievement_honest_gold_name;
case 'achievement_marathon_name':
return l10n.achievement_marathon_name;
case 'achievement_century_name':
return l10n.achievement_century_name;
case 'achievement_master_name':
return l10n.achievement_master_name;
case 'achievement_persistence_star_name':
return l10n.achievement_persistence_star_name;
case 'achievement_monthly_habit_name':
return l10n.achievement_monthly_habit_name;
case 'achievement_centurion_name':
return l10n.achievement_centurion_name;
case 'achievement_year_warrior_name':
return l10n.achievement_year_warrior_name;
default:
return key;
}
}
/// Get localized achievement description by key
String _getLocalizedAchievementDesc(AppLocalizations l10n, String key) {
switch (key) {
case 'achievement_first_session_desc':
return l10n.achievement_first_session_desc;
case 'achievement_sessions_10_desc':
return l10n.achievement_sessions_10_desc;
case 'achievement_sessions_50_desc':
return l10n.achievement_sessions_50_desc;
case 'achievement_sessions_100_desc':
return l10n.achievement_sessions_100_desc;
case 'achievement_honest_bronze_desc':
return l10n.achievement_honest_bronze_desc;
case 'achievement_honest_silver_desc':
return l10n.achievement_honest_silver_desc;
case 'achievement_honest_gold_desc':
return l10n.achievement_honest_gold_desc;
case 'achievement_marathon_desc':
return l10n.achievement_marathon_desc;
case 'achievement_century_desc':
return l10n.achievement_century_desc;
case 'achievement_master_desc':
return l10n.achievement_master_desc;
case 'achievement_persistence_star_desc':
return l10n.achievement_persistence_star_desc;
case 'achievement_monthly_habit_desc':
return l10n.achievement_monthly_habit_desc;
case 'achievement_centurion_desc':
return l10n.achievement_centurion_desc;
case 'achievement_year_warrior_desc':
return l10n.achievement_year_warrior_desc;
default:
return key;
}
}
}

View File

@@ -0,0 +1,581 @@
import 'package:flutter/material.dart';
import '../l10n/app_localizations.dart';
import '../theme/app_colors.dart';
import '../theme/app_text_styles.dart';
import '../models/focus_session.dart';
import '../models/achievement_config.dart';
import '../services/points_service.dart';
import '../services/storage_service.dart';
import '../services/encouragement_service.dart';
import '../services/di.dart';
/// Session Detail Screen - Shows detailed information about a past focus session
class SessionDetailScreen extends StatelessWidget {
final FocusSession session;
const SessionDetailScreen({super.key, required this.session});
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final pointsService = getIt<PointsService>();
final storageService = getIt<StorageService>();
final encouragementService = getIt<EncouragementService>();
// Calculate points for this session
final pointsBreakdown = pointsService.calculateSessionPoints(session);
final pointsEarned = pointsBreakdown['total'] as int;
final basePoints = pointsBreakdown['basePoints'] as int;
final honestyBonus = pointsBreakdown['honestyBonus'] as int;
// Get user progress to show total points
final progress = storageService.getUserProgress();
final encouragement = encouragementService.getRandomMessage();
// Find achievements that might have been unlocked during this session
final sessionAchievements = _findSessionAchievements(
session,
storageService,
);
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(
title: const Text('会话详情'),
backgroundColor: AppColors.background,
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 20),
// Session Date and Time
_buildSessionHeader(context, l10n),
const SizedBox(height: 32),
// Focused Time Section
Text(l10n.youFocusedFor, style: AppTextStyles.headline),
const SizedBox(height: 8),
Text(
l10n.minutesValue(
session.actualMinutes,
l10n.minutes(session.actualMinutes),
),
style: AppTextStyles.largeNumber,
),
const SizedBox(height: 32),
// Points Earned Section
_buildPointsCard(
context,
l10n,
pointsEarned,
basePoints,
honestyBonus,
),
const SizedBox(height: 16),
// Session Stats Card
Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('会话统计', style: AppTextStyles.headline),
const SizedBox(height: 16),
_buildStatRow(
icon: '⏱️',
label: '计划时长',
value: l10n.minutesValue(
session.durationMinutes,
l10n.minutes(session.durationMinutes),
),
),
const SizedBox(height: 12),
_buildStatRow(
icon: '',
label: '实际专注',
value: l10n.minutesValue(
session.actualMinutes,
l10n.minutes(session.actualMinutes),
),
),
const SizedBox(height: 12),
_buildStatRow(
icon: '🤚',
label: '分心次数',
value: l10n.distractionsCount(
session.distractionCount,
l10n.times(session.distractionCount),
),
),
const SizedBox(height: 12),
_buildStatRow(
icon: '🏁',
label: '状态',
value: session.completed
? l10n.completed
: l10n.stoppedEarly,
),
const SizedBox(height: 20),
Text(
'"$encouragement"',
style: AppTextStyles.encouragementQuote,
),
],
),
),
const SizedBox(height: 16),
// Achievements Unlocked Section
if (sessionAchievements.isNotEmpty)
..._buildAchievementCards(context, l10n, sessionAchievements),
const SizedBox(height: 24),
// Total Points Display
Text(
l10n.totalPoints(progress.totalPoints),
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
fontWeight: FontWeight.w600,
color: AppColors.primary,
),
),
const SizedBox(height: 40),
],
),
),
),
),
);
}
/// Build session header with date and time
Widget _buildSessionHeader(BuildContext context, AppLocalizations l10n) {
final dateStr = session.startTime.toLocal().toString().split(' ')[0];
final timeStr = session.startTime
.toLocal()
.toString()
.split(' ')[1]
.substring(0, 5);
return Container(
width: double.infinity,
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(16),
),
child: Column(
children: [
Text(dateStr, style: AppTextStyles.headline),
const SizedBox(height: 8),
Text(timeStr, style: AppTextStyles.largeNumber),
],
),
);
}
/// Build points earned card
Widget _buildPointsCard(
BuildContext context,
AppLocalizations l10n,
int pointsEarned,
int basePoints,
int honestyBonus,
) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: AppColors.primary.withValues(alpha: 0.3),
width: 2,
),
),
child: Column(
children: [
// Main points display
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
l10n.earnedPoints,
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 18,
color: AppColors.textSecondary,
),
),
const SizedBox(width: 8),
Text(
'+$pointsEarned',
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 28,
fontWeight: FontWeight.bold,
color: AppColors.primary,
),
),
const Text('', style: TextStyle(fontSize: 24)),
],
),
const SizedBox(height: 16),
Divider(
thickness: 1,
color: AppColors.textSecondary.withValues(alpha: 0.2),
),
const SizedBox(height: 12),
// Points breakdown
_buildPointRow(l10n.basePoints, '+$basePoints', AppColors.success),
if (honestyBonus > 0) ...[
const SizedBox(height: 8),
_buildPointRow(
l10n.honestyBonus,
'+$honestyBonus',
AppColors.success,
subtitle: l10n.distractionsRecorded(
session.distractionCount,
l10n.distractions(session.distractionCount),
),
),
],
],
),
);
}
/// Build a single point row in the breakdown
Widget _buildPointRow(
String label,
String points,
Color color, {
String? subtitle,
}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Column(
children: [
Row(
children: [
Text(
'├─ ',
style: TextStyle(
color: AppColors.textSecondary.withValues(alpha: 0.4),
fontFamily: 'Nunito',
),
),
Text(
label,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
color: AppColors.textSecondary,
),
),
const Spacer(),
Text(
points,
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
fontWeight: FontWeight.w600,
color: color,
),
),
],
),
if (subtitle != null)
Padding(
padding: const EdgeInsets.only(left: 24, top: 4),
child: Row(
children: [
Text(
subtitle,
style: TextStyle(
fontFamily: 'Nunito',
fontSize: 12,
color: AppColors.textSecondary.withValues(alpha: 0.7),
),
),
],
),
),
],
),
);
}
/// Build a single stat row
Widget _buildStatRow({
required String icon,
required String label,
required String value,
}) {
return Row(
children: [
Text(icon, style: const TextStyle(fontSize: 20)),
const SizedBox(width: 12),
Text(label, style: AppTextStyles.bodyText),
const Spacer(),
Text(
value,
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
),
),
],
);
}
/// Find achievements that might have been unlocked during this session
List<AchievementConfig> _findSessionAchievements(
FocusSession session,
StorageService storageService,
) {
final allAchievements = AchievementConfig.all;
final unlockedAchievements = storageService
.getUserProgress()
.unlockedAchievements;
final sessionAchievements = <AchievementConfig>[];
// Get all sessions to determine the state before this one
final allSessions = storageService.getAllSessions();
final sessionIndex = allSessions.indexOf(session);
// Calculate stats before this session
int sessionsBefore = sessionIndex;
int distractionsBefore = allSessions
.sublist(0, sessionIndex)
.fold(0, (sum, s) => sum + s.distractionCount);
int minutesBefore = allSessions
.sublist(0, sessionIndex)
.fold(0, (sum, s) => sum + s.actualMinutes);
// Check which achievements might have been unlocked by this session
for (final achievement in allAchievements) {
// Skip if not unlocked
if (!unlockedAchievements.containsKey(achievement.id)) {
continue;
}
// Check if this session could have unlocked the achievement
bool unlockedByThisSession = false;
switch (achievement.type) {
case AchievementType.sessionCount:
unlockedByThisSession =
sessionsBefore < achievement.requiredValue &&
(sessionsBefore + 1) >= achievement.requiredValue;
break;
case AchievementType.distractionCount:
unlockedByThisSession =
distractionsBefore < achievement.requiredValue &&
(distractionsBefore + session.distractionCount) >=
achievement.requiredValue;
break;
case AchievementType.totalMinutes:
unlockedByThisSession =
minutesBefore < achievement.requiredValue &&
(minutesBefore + session.actualMinutes) >=
achievement.requiredValue;
break;
case AchievementType.consecutiveDays:
// Consecutive days are not directly related to a single session
// but rather to check-ins, so we'll skip this type
break;
}
if (unlockedByThisSession) {
sessionAchievements.add(achievement);
}
}
return sessionAchievements;
}
/// Build achievement cards for achievements unlocked in this session
List<Widget> _buildAchievementCards(
BuildContext context,
AppLocalizations l10n,
List<AchievementConfig> achievements,
) {
return [
Text('解锁的成就', style: AppTextStyles.headline),
const SizedBox(height: 16),
...achievements.map((achievement) {
return Container(
margin: const EdgeInsets.only(bottom: 16),
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFFFFD700), Color(0xFFFFC107)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.orange.withValues(alpha: 0.4),
blurRadius: 20,
offset: const Offset(0, 8),
),
],
),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(achievement.icon, style: const TextStyle(fontSize: 32)),
const SizedBox(width: 12),
Text(
'成就解锁!',
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
],
),
const SizedBox(height: 12),
Text(
_getLocalizedAchievementName(l10n, achievement.nameKey),
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
const SizedBox(height: 4),
Text(
_getLocalizedAchievementDesc(l10n, achievement.descKey),
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 14,
color: Colors.white,
),
textAlign: TextAlign.center,
),
if (achievement.bonusPoints > 0)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'+${achievement.bonusPoints} 积分',
style: const TextStyle(
fontFamily: 'Nunito',
fontSize: 16,
fontWeight: FontWeight.w600,
color: Colors.white,
),
),
),
],
),
);
}),
];
}
/// Get localized achievement name by key
String _getLocalizedAchievementName(AppLocalizations l10n, String key) {
switch (key) {
case 'achievement_first_session_name':
return l10n.achievement_first_session_name;
case 'achievement_sessions_10_name':
return l10n.achievement_sessions_10_name;
case 'achievement_sessions_50_name':
return l10n.achievement_sessions_50_name;
case 'achievement_sessions_100_name':
return l10n.achievement_sessions_100_name;
case 'achievement_honest_bronze_name':
return l10n.achievement_honest_bronze_name;
case 'achievement_honest_silver_name':
return l10n.achievement_honest_silver_name;
case 'achievement_honest_gold_name':
return l10n.achievement_honest_gold_name;
case 'achievement_marathon_name':
return l10n.achievement_marathon_name;
case 'achievement_century_name':
return l10n.achievement_century_name;
case 'achievement_master_name':
return l10n.achievement_master_name;
case 'achievement_persistence_star_name':
return l10n.achievement_persistence_star_name;
case 'achievement_monthly_habit_name':
return l10n.achievement_monthly_habit_name;
case 'achievement_centurion_name':
return l10n.achievement_centurion_name;
case 'achievement_year_warrior_name':
return l10n.achievement_year_warrior_name;
default:
return key;
}
}
/// Get localized achievement description by key
String _getLocalizedAchievementDesc(AppLocalizations l10n, String key) {
switch (key) {
case 'achievement_first_session_desc':
return l10n.achievement_first_session_desc;
case 'achievement_sessions_10_desc':
return l10n.achievement_sessions_10_desc;
case 'achievement_sessions_50_desc':
return l10n.achievement_sessions_50_desc;
case 'achievement_sessions_100_desc':
return l10n.achievement_sessions_100_desc;
case 'achievement_honest_bronze_desc':
return l10n.achievement_honest_bronze_desc;
case 'achievement_honest_silver_desc':
return l10n.achievement_honest_silver_desc;
case 'achievement_honest_gold_desc':
return l10n.achievement_honest_gold_desc;
case 'achievement_marathon_desc':
return l10n.achievement_marathon_desc;
case 'achievement_century_desc':
return l10n.achievement_century_desc;
case 'achievement_master_desc':
return l10n.achievement_master_desc;
case 'achievement_persistence_star_desc':
return l10n.achievement_persistence_star_desc;
case 'achievement_monthly_habit_desc':
return l10n.achievement_monthly_habit_desc;
case 'achievement_centurion_desc':
return l10n.achievement_centurion_desc;
case 'achievement_year_warrior_desc':
return l10n.achievement_year_warrior_desc;
default:
return key;
}
}
}