From 6555ec5e171f5ad02a3ec0318e3e5b6cfe71a4df Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Thu, 9 Apr 2026 16:48:10 +0700 Subject: [PATCH 01/11] feat(UserProfile): build screen UserProfile # Conflicts: # src/lib/features/main/view/screens/main_screen.dart --- src/lib/core/theme/app_theme.dart | 87 +++++++++++ .../main/view/screens/main_screen.dart | 9 +- .../user/model/user_profile_model.dart | 65 ++++++++ .../features/user/service/user_service.dart | 19 +++ .../features/user/view/user_profile_view.dart | 139 ++++++++++++++++++ .../user/view/widgets/logout_button.dart | 45 ++++++ .../user/view/widgets/profile_header.dart | 84 +++++++++++ .../user/view/widgets/settings_list_tile.dart | 55 +++++++ .../user/view/widgets/settings_section.dart | 40 +++++ .../features/user/view/widgets/stat_card.dart | 52 +++++++ .../viewmodel/user_profile_viewmodel.dart | 73 +++++++++ src/lib/main.dart | 2 +- ...20260409084009_create_user_profile_rpc.sql | 58 ++++++++ 13 files changed, 726 insertions(+), 2 deletions(-) create mode 100644 src/lib/core/theme/app_theme.dart create mode 100644 src/lib/features/user/model/user_profile_model.dart create mode 100644 src/lib/features/user/service/user_service.dart create mode 100644 src/lib/features/user/view/user_profile_view.dart create mode 100644 src/lib/features/user/view/widgets/logout_button.dart create mode 100644 src/lib/features/user/view/widgets/profile_header.dart create mode 100644 src/lib/features/user/view/widgets/settings_list_tile.dart create mode 100644 src/lib/features/user/view/widgets/settings_section.dart create mode 100644 src/lib/features/user/view/widgets/stat_card.dart create mode 100644 src/lib/features/user/viewmodel/user_profile_viewmodel.dart create mode 100644 supabase/migrations/20260409084009_create_user_profile_rpc.sql diff --git a/src/lib/core/theme/app_theme.dart b/src/lib/core/theme/app_theme.dart new file mode 100644 index 0000000..1da88ec --- /dev/null +++ b/src/lib/core/theme/app_theme.dart @@ -0,0 +1,87 @@ +import 'package:flutter/material.dart'; + +class AppTheme { + // ========================================================= + // ☀️ LIGHT THEME DICTIONARY + // Inherited from the legacy AppColors class + // ========================================================= + static final ThemeData lightTheme = ThemeData( + brightness: Brightness.light, + scaffoldBackgroundColor: const Color(0xFFF4F6F9), // Legacy: AppColors.background + + colorScheme: const ColorScheme.light( + // Brand Colors + primary: Color(0xFF5A8DF3), // Legacy: AppColors.primary + secondary: Color(0xFF4A90E2), // Legacy: AppColors.primaryBlue + + // Background & Surface Colors + // Note: 'background' is deprecated, scaffoldBackgroundColor handles the main background. + surface: Colors.white, // Legacy: AppColors.taskCardBg / white + surfaceContainerHighest: Color(0xFFE0F7FA), // Legacy: AppColors.backgroundBlue (Tinted background) + + // Text Colors + onSurface: Color(0xFF2D3440), // Legacy: AppColors.textDark + onSurfaceVariant: Color(0xFF757575), // Legacy: AppColors.grayText / textSecondary + + // Border & Status Colors + outline: Color(0xFFE2E8F0), // Legacy: AppColors.border + error: Colors.redAccent, // Legacy: AppColors.error + tertiary: Colors.green, // Using Tertiary for Success (Green) + ), + + appBarTheme: const AppBarTheme( + backgroundColor: Colors.transparent, + elevation: 0, + iconTheme: IconThemeData(color: Color(0xFF5A8DF3)), + titleTextStyle: TextStyle( + color: Color(0xFF5A8DF3), + fontWeight: FontWeight.w800, + fontSize: 20, + ), + ), + + dividerTheme: const DividerThemeData(color: Color(0xFFE2E8F0)), + ); + + // ========================================================= + // 🌙 DARK THEME DICTIONARY + // Extracted from the provided Stitch Design System + // ========================================================= + static final ThemeData darkTheme = ThemeData( + brightness: Brightness.dark, + scaffoldBackgroundColor: const Color(0xFF0F172A), // Neutral Slate Dark + + colorScheme: const ColorScheme.dark( + // Brand Colors (Slightly brighter to stand out on dark background) + primary: Color(0xFF60A5FA), // Bright Blue + secondary: Color(0xFF61789A), // Slate Blue + + // Background & Surface Colors + // Note: 'background' is deprecated, scaffoldBackgroundColor handles the main background. + surface: Color(0xFF1E293B), // Slightly lighter than background, used for Cards + surfaceContainerHighest: Color(0xFF162032), // Dark mode counterpart for backgroundBlue + + // Text Colors + onSurface: Colors.white, // Primary text (White) + onSurfaceVariant: Color(0xFF94A3B8), // Secondary text (Light Slate) + + // Border, Status & Highlight Colors + outline: Color(0xFF334155), // Faint Card Border + error: Color(0xFFF87171), // Pinkish Red (Similar to Trash Icon) + tertiary: Color(0xFFD19900), // Mustard Yellow (Similar to Edit Pencil Icon) + ), + + appBarTheme: const AppBarTheme( + backgroundColor: Colors.transparent, + elevation: 0, + iconTheme: IconThemeData(color: Color(0xFF60A5FA)), + titleTextStyle: TextStyle( + color: Color(0xFF60A5FA), + fontWeight: FontWeight.w800, + fontSize: 20, + ), + ), + + dividerTheme: const DividerThemeData(color: Color(0xFF334155)), + ); +} \ No newline at end of file diff --git a/src/lib/features/main/view/screens/main_screen.dart b/src/lib/features/main/view/screens/main_screen.dart index 8c8cffe..033f2bf 100644 --- a/src/lib/features/main/view/screens/main_screen.dart +++ b/src/lib/features/main/view/screens/main_screen.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:task_management_app/features/statistics/viewmodel/statistics_viewmodel.dart'; import 'package:task_management_app/features/tasks/view/screens/home_screen.dart'; import 'settings_screen.dart'; +import 'package:task_management_app/features/user/viewmodel/user_profile_viewmodel.dart'; import '../../../../core/theme/app_colors.dart'; import '../../../note/view/focus_screen.dart'; import '../../../note/viewmodel/focus_viewmodel.dart'; @@ -9,6 +10,8 @@ import '../../../statistics/view/screens/statistics_screen.dart'; // import '../../../tasks/view/screens/home_screen.dart'; import 'package:provider/provider.dart'; +import '../../../user/view/user_profile_view.dart'; + class MainScreen extends StatefulWidget { const MainScreen({super.key}); @@ -30,6 +33,10 @@ class _MainScreenState extends State { create: (_) => StatisticsViewmodel(), child: const StatisticsScreen(), ), + ChangeNotifierProvider( + create: (_) => UserProfileViewModel()..loadProfile(), + child: const UserProfileView(), + ), const SettingsScreen(), ]; @@ -56,7 +63,7 @@ class _MainScreenState extends State { _buildNavItem(Icons.calendar_today_rounded, 'Lịch', 1), _buildNavItem(Icons.timer_rounded, 'Tập trung', 2), _buildNavItem(Icons.bar_chart_rounded, 'Thống kê', 3), - _buildNavItem(Icons.settings_rounded, 'Cài đặt', 4), + _buildNavItem(Icons.person_2_rounded, 'Cá nhân', 4), ], ), ), diff --git a/src/lib/features/user/model/user_profile_model.dart b/src/lib/features/user/model/user_profile_model.dart new file mode 100644 index 0000000..c808f55 --- /dev/null +++ b/src/lib/features/user/model/user_profile_model.dart @@ -0,0 +1,65 @@ +class UserProfileModel { + final String id; + final String name; + final int tasksDone; + final int streaks; + final String avatarUrl; + bool isNotificationEnabled; + String appearance; + + UserProfileModel({ + required this.id, + required this.name, + required this.tasksDone, + required this.streaks, + required this.avatarUrl, + this.isNotificationEnabled = true, + this.appearance = 'Light', + }); + + factory UserProfileModel.fromJson(Map json) { + return UserProfileModel( + // Dùng as String? để ép kiểu an toàn, kèm ?? để gán giá trị mặc định nếu bị null + id: json['id'] as String? ?? '', + name: json['name'] as String? ?? 'Unknown User', + tasksDone: json['tasksDone'] as int? ?? 0, + streaks: json['streaks'] as int? ?? 0, + avatarUrl: json['avatarUrl'] as String? ?? '', + isNotificationEnabled: json['isNotificationEnabled'] as bool? ?? true, + appearance: json['appearance'] as String? ?? 'Light', + ); + } + + + Map toJson() { + return { + 'id': id, + 'name': name, + 'tasksDone': tasksDone, + 'streaks': streaks, + 'avatarUrl': avatarUrl, + 'isNotificationEnabled': isNotificationEnabled, + 'appearance': appearance, + }; + } + + UserProfileModel copyWith({ + String? id, + String? name, + int? tasksDone, + int? streaks, + String? avatarUrl, + bool? isNotificationEnabled, + String? appearance, + }) { + return UserProfileModel( + id: id ?? this.id, + name: name ?? this.name, + tasksDone: tasksDone ?? this.tasksDone, + streaks: streaks ?? this.streaks, + avatarUrl: avatarUrl ?? this.avatarUrl, + isNotificationEnabled: isNotificationEnabled ?? this.isNotificationEnabled, + appearance: appearance ?? this.appearance, + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/service/user_service.dart b/src/lib/features/user/service/user_service.dart new file mode 100644 index 0000000..9a6c0d7 --- /dev/null +++ b/src/lib/features/user/service/user_service.dart @@ -0,0 +1,19 @@ +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../model/user_profile_model.dart'; + +class UserService { + final SupabaseClient _supabase = Supabase.instance.client; + /// Simulates fetching user profile data with a fake network delay + Future fetchUserProfile() async { + // Mimic API call delay for smooth state switching + try{ + final response = await _supabase.rpc('get_user_profile_stats'); + response['id'] = _supabase.auth.currentUser!.id; + return UserProfileModel.fromJson(response); + } + catch(e){ + throw Exception("Failed to fetch user profile: $e"); + } + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/user_profile_view.dart b/src/lib/features/user/view/user_profile_view.dart new file mode 100644 index 0000000..5dcdb32 --- /dev/null +++ b/src/lib/features/user/view/user_profile_view.dart @@ -0,0 +1,139 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../../../core/theme/app_colors.dart'; + +import '../viewmodel/user_profile_viewmodel.dart'; +import 'widgets/profile_header.dart'; +import 'widgets/stat_card.dart'; +import 'widgets/settings_section.dart'; +import 'widgets/settings_list_tile.dart'; +import 'widgets/logout_button.dart'; + +class UserProfileView extends StatelessWidget { + const UserProfileView({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.background, + appBar: AppBar( + backgroundColor: AppColors.background, + elevation: 0, + centerTitle: true, + scrolledUnderElevation: 0, + title: const Text( + 'Profile', + style: TextStyle( + color: AppColors.primaryBlue, + fontWeight: FontWeight.w800, + fontSize: 20, + ), + ), + actions: [ + IconButton( + icon: const Icon(Icons.settings, color: AppColors.primaryBlue), + onPressed: () {}, + splashRadius: 24, + ), + ], + ), + body: Consumer( + builder: (context, vm, child) { + return AnimatedSwitcher( + duration: const Duration(milliseconds: 300), + child: vm.isLoading + ? const Center( + key: ValueKey('loading'), + child: CircularProgressIndicator(color: AppColors.primaryBlue), + ) + : vm.user == null + ? const Center( + key: ValueKey('error'), + child: Text("Error loading profile"), + ) + : _buildProfileContent(context, vm), + ); + }, + ), + ); + } + + Widget _buildProfileContent(BuildContext context, UserProfileViewModel vm) { + final user = vm.user!; + return SingleChildScrollView( + key: const ValueKey('content'), + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.fromLTRB(24, 8, 24, 40), + child: Column( + children: [ + // 1. Header (Avatar & Name) + ProfileHeader(user: user), + const SizedBox(height: 32), + + // 2. Stats Row + Row( + children: [ + Expanded( + child: StatCard( + value: user.tasksDone.toString(), + label: 'Tasks Done', + onTap: () {}, + ), + ), + const SizedBox(width: 16), + Expanded( + child: StatCard( + value: user.streaks.toString(), + label: 'Streaks', + onTap: () {}, + ), + ), + ], + ), + const SizedBox(height: 32), + + SettingsSection( + title: 'Preferences', + children: [ + SettingsListTile( + icon: Icons.notifications, + title: 'Notifications', + iconBgColor: AppColors.border, + iconColor: AppColors.grayText, + onTap: () => vm.toggleNotification(!user.isNotificationEnabled), + trailing: Switch( + value: user.isNotificationEnabled, + activeColor: AppColors.white, + activeTrackColor: AppColors.primaryBlue, + inactiveThumbColor: AppColors.grayText, + inactiveTrackColor: AppColors.border, + onChanged: (val) => vm.toggleNotification(val), + ), + ), + const Divider(height: 1, indent: 64, endIndent: 24, color: AppColors.border), + SettingsListTile( + icon: Icons.dark_mode, + title: 'Appearance', + iconBgColor: AppColors.border, + iconColor: AppColors.grayText, + trailing: Text( + user.appearance, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: AppColors.grayText, + ), + ), + onTap: () {}, + ), + ], + ), + const SizedBox(height: 40), + + // 4. Logout Button + LogoutButton(onPressed: () => vm.logout(context)), + ], + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/logout_button.dart b/src/lib/features/user/view/widgets/logout_button.dart new file mode 100644 index 0000000..6484722 --- /dev/null +++ b/src/lib/features/user/view/widgets/logout_button.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart'; +import '../../../../core/theme/app_colors.dart'; + +class LogoutButton extends StatelessWidget { + final VoidCallback onPressed; + + const LogoutButton({super.key, required this.onPressed}); + + @override + Widget build(BuildContext context) { + return Material( + color: AppColors.error.withOpacity(0.05), + borderRadius: BorderRadius.circular(24), + child: InkWell( + onTap: onPressed, + borderRadius: BorderRadius.circular(24), + splashColor: AppColors.error.withOpacity(0.1), + highlightColor: AppColors.error.withOpacity(0.05), + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 20), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(24), + border: Border.all(color: AppColors.error.withOpacity(0.2)), + ), + child: const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.logout, color: AppColors.error, size: 22), + SizedBox(width: 12), + Text( + 'Logout', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: AppColors.error, + ), + ), + ], + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/profile_header.dart b/src/lib/features/user/view/widgets/profile_header.dart new file mode 100644 index 0000000..4607c39 --- /dev/null +++ b/src/lib/features/user/view/widgets/profile_header.dart @@ -0,0 +1,84 @@ +import 'package:flutter/material.dart'; +import '../../../../core/theme/app_colors.dart'; // Adjust path based on your project structure +import '../../model/user_profile_model.dart'; + +class ProfileHeader extends StatelessWidget { + final UserProfileModel user; + + const ProfileHeader({super.key, required this.user}); + + @override + Widget build(BuildContext context) { + return Column( + children: [ + Stack( + alignment: Alignment.bottomRight, + children: [ + // Rounded Square Avatar + Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(32), + boxShadow: [ + BoxShadow( + color: AppColors.primaryBlue.withOpacity(0.15), + blurRadius: 20, + offset: const Offset(0, 10), + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(32), + child: Image.network( + user.avatarUrl, + width: 120, + height: 120, + fit: BoxFit.cover, + // Smooth image loading transition + frameBuilder: (context, child, frame, wasSynchronouslyLoaded) { + if (wasSynchronouslyLoaded) return child; + return AnimatedOpacity( + opacity: frame == null ? 0 : 1, + duration: const Duration(milliseconds: 500), + curve: Curves.easeOut, + child: child, + ); + }, + ), + ), + ), + // Edit Button with Ripple + Material( + color: AppColors.primaryBlue, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: const BorderSide(color: AppColors.background, width: 4), + ), + child: InkWell( + borderRadius: BorderRadius.circular(12), + onTap: () { + // TODO: Handle Edit Profile action + }, + child: const Padding( + padding: EdgeInsets.all(8.0), + child: Icon(Icons.edit, color: AppColors.white, size: 20), + ), + ), + ), + ], + ), + const SizedBox(height: 20), + + // Name Only + Text( + user.name, + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.w800, + color: AppColors.textDark, + ), + ), + // Badges row removed here + ], + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/settings_list_tile.dart b/src/lib/features/user/view/widgets/settings_list_tile.dart new file mode 100644 index 0000000..2472243 --- /dev/null +++ b/src/lib/features/user/view/widgets/settings_list_tile.dart @@ -0,0 +1,55 @@ +import 'package:flutter/material.dart'; +import '../../../../core/theme/app_colors.dart'; + +class SettingsListTile extends StatelessWidget { + final IconData icon; + final String title; + final Widget trailing; + final Color iconBgColor; + final Color iconColor; + final VoidCallback? onTap; + + const SettingsListTile({ + super.key, + required this.icon, + required this.title, + required this.trailing, + this.iconBgColor = AppColors.backgroundBlue, + this.iconColor = AppColors.primaryBlue, + this.onTap, + }); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: iconBgColor, + shape: BoxShape.circle, + ), + child: Icon(icon, color: iconColor, size: 22), + ), + const SizedBox(width: 16), + Expanded( + child: Text( + title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: AppColors.textDark, + ), + ), + ), + trailing, + ], + ), + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/settings_section.dart b/src/lib/features/user/view/widgets/settings_section.dart new file mode 100644 index 0000000..be81a66 --- /dev/null +++ b/src/lib/features/user/view/widgets/settings_section.dart @@ -0,0 +1,40 @@ +import 'package:flutter/material.dart'; +import '../../../../core/theme/app_colors.dart'; + +class SettingsSection extends StatelessWidget { + final String title; + final List children; + + const SettingsSection({super.key, required this.title, required this.children}); + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(left: 16, bottom: 12), + child: Text( + title.toUpperCase(), + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.bold, + color: AppColors.grayText, + letterSpacing: 1.2, + ), + ), + ), + Material( + color: AppColors.white, + borderRadius: BorderRadius.circular(24), + child: ClipRRect( + borderRadius: BorderRadius.circular(24), + child: Column( + children: children, + ), + ), + ), + ], + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/stat_card.dart b/src/lib/features/user/view/widgets/stat_card.dart new file mode 100644 index 0000000..2bfb80c --- /dev/null +++ b/src/lib/features/user/view/widgets/stat_card.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; +import '../../../../core/theme/app_colors.dart'; + +class StatCard extends StatelessWidget { + final String value; + final String label; + final VoidCallback? onTap; + + const StatCard({super.key, required this.value, required this.label, this.onTap}); + + @override + Widget build(BuildContext context) { + return Material( + color: AppColors.white, + borderRadius: BorderRadius.circular(24), + elevation: 0, + child: InkWell( + onTap: onTap ?? () {}, // Interactive ripple effect + borderRadius: BorderRadius.circular(24), + child: Container( + padding: const EdgeInsets.symmetric(vertical: 24), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(24), + border: Border.all(color: AppColors.border.withOpacity(0.5)), + ), + child: Column( + children: [ + Text( + value, + style: const TextStyle( + fontSize: 28, + fontWeight: FontWeight.w800, + color: AppColors.primaryBlue, + ), + ), + const SizedBox(height: 4), + Text( + label.toUpperCase(), + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: AppColors.grayText, + letterSpacing: 1.2, + ), + ), + ], + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart new file mode 100644 index 0000000..6c8e05f --- /dev/null +++ b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; +import '../../auth/presentation/view/auth_gate.dart'; +import '../model/user_profile_model.dart'; +import '../service/user_service.dart'; + +class UserProfileViewModel extends ChangeNotifier { + final UserService _userService = UserService(); + + final _supabase = Supabase.instance.client; + + UserProfileModel? _user; + UserProfileModel? get user => _user; + + bool _isLoading = true; + bool get isLoading => _isLoading; + + /// Load profile data + Future loadProfile() async { + _isLoading = true; + notifyListeners(); + + try { + _user = await _userService.fetchUserProfile(); + } catch (e) { + debugPrint("Error loading profile: $e"); + } finally { + _isLoading = false; + notifyListeners(); + } + } + + /// Toggle notification preference + void toggleNotification(bool value) { + if (_user != null) { + _user!.isNotificationEnabled = value; + notifyListeners(); + // Ghi chú: Có thể dùng SharedPreferences để lưu local setting này + } + } + + /// Handle theme/appearance change + void updateAppearance(String newAppearance) { + if (_user != null) { + _user!.appearance = newAppearance; + notifyListeners(); + // Ghi chú: Chỗ này thường sẽ gọi Provider quản lý Theme tổng của App + } + } + + + Future logout(BuildContext context) async { + try { + await _supabase.auth.signOut(); + debugPrint("Đã clear session trên Supabase."); + + if (context.mounted) { + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (context) => const AuthGate()), + (route) => false, + ); + } + + } catch (e) { + debugPrint("Lỗi đăng xuất: $e"); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Lỗi đăng xuất: $e')), + ); + } + } + } +} \ No newline at end of file diff --git a/src/lib/main.dart b/src/lib/main.dart index e0f3857..c726b17 100644 --- a/src/lib/main.dart +++ b/src/lib/main.dart @@ -55,7 +55,7 @@ class TaskApp extends StatelessWidget { labelLarge: TextStyle(fontSize: 16, color: AppColors.primaryBlue), ), ), - home: const AuthGate(), + home: const MainScreen(), debugShowCheckedModeBanner: false, ); } diff --git a/supabase/migrations/20260409084009_create_user_profile_rpc.sql b/supabase/migrations/20260409084009_create_user_profile_rpc.sql new file mode 100644 index 0000000..235c129 --- /dev/null +++ b/supabase/migrations/20260409084009_create_user_profile_rpc.sql @@ -0,0 +1,58 @@ +CREATE OR REPLACE FUNCTION get_user_profile_stats() +RETURNS JSON +LANGUAGE plpgsql +SECURITY INVOKER -- Chạy với quyền của user hiện tại (Tôn trọng RLS) +AS $$ +DECLARE + v_user_id UUID; + v_username TEXT; + v_avatar TEXT; + v_tasks_done INT; + v_current_streak INT; +BEGIN + v_user_id := auth.uid(); + + IF v_user_id IS NULL THEN + RAISE EXCEPTION 'User not authenticated'; + END IF; + + SELECT username, avatar INTO v_username, v_avatar + FROM public.profile + WHERE id = v_user_id; + + + SELECT COUNT(*) INTO v_tasks_done + FROM public.task + WHERE profile_id = v_user_id AND status = 1; + + + WITH completed_dates AS ( + -- Get the day that had task done + SELECT DISTINCT DATE(updated_at AT TIME ZONE 'UTC') AS task_date + FROM public.task + WHERE profile_id = v_user_id AND status = 1 + ), + streak_groups AS ( + SELECT task_date, + task_date - (ROW_NUMBER() OVER (ORDER BY task_date))::INT AS grp + FROM completed_dates + ), + streak_counts AS ( + -- Calculate streak length for each group + SELECT grp, MAX(task_date) as end_date, COUNT(*) as streak_length + FROM streak_groups + GROUP BY grp + ) + -- get streak if the end date is within the yesterday + SELECT COALESCE(MAX(streak_length), 0) INTO v_current_streak + FROM streak_counts + WHERE end_date >= (CURRENT_DATE - INTERVAL '1 day'); + + RETURN json_build_object( + 'name', COALESCE(v_username, 'Unknown User'), + 'avatarUrl', COALESCE(v_avatar, ''), + 'tasksDone', COALESCE(v_tasks_done, 0), + 'streaks', COALESCE(v_current_streak, 0) + ); +END; +$$; \ No newline at end of file From bacf05afde6fd1becde5537aecee755037434452 Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Thu, 9 Apr 2026 17:33:25 +0700 Subject: [PATCH 02/11] feat: switch dark/light theme --- src/lib/core/theme/auth_layout_template.dart | 84 ++++++++++-------- src/lib/core/theme/custom_text_field.dart | 19 ++-- src/lib/core/theme/theme_provider.dart | 57 ++++++++++++ src/lib/core/widgets/custom_input_field.dart | 8 +- .../features/auth/otp_verification_view.dart | 65 ++++++++------ .../view/forgot_password_view.dart | 39 +++++--- .../auth/presentation/view/login_view.dart | 70 ++++++++++++--- .../presentation/view/new_password_view.dart | 41 +++++++-- .../view/otp_verification_view.dart | 88 ++++++++++++++----- .../auth/presentation/view/register_view.dart | 33 +++++-- .../main/view/screens/main_screen.dart | 25 ++++-- src/lib/features/note/view/focus_screen.dart | 41 +++++++-- src/lib/features/note/view/focus_widget.dart | 72 +++++++++++---- .../view/screens/statistics_screen.dart | 25 ++++-- .../view/widgets/statistics_widgets.dart | 65 ++++++++++---- .../view/screens/create_task_screen.dart | 17 ++-- .../tasks/view/screens/home_screen.dart | 25 ++++-- .../view/screens/task_detail_screen.dart | 14 +-- .../tasks/view/widgets/task_widgets.dart | 27 ++++-- .../features/user/view/user_profile_view.dart | 61 ++++++++----- .../user/view/widgets/logout_button.dart | 19 ++-- .../user/view/widgets/profile_header.dart | 78 +++++++++++----- .../user/view/widgets/settings_list_tile.dart | 21 +++-- .../user/view/widgets/settings_section.dart | 7 +- .../features/user/view/widgets/stat_card.dart | 13 ++- .../viewmodel/user_profile_viewmodel.dart | 34 +++++-- src/lib/main.dart | 30 +++---- 27 files changed, 770 insertions(+), 308 deletions(-) create mode 100644 src/lib/core/theme/theme_provider.dart diff --git a/src/lib/core/theme/auth_layout_template.dart b/src/lib/core/theme/auth_layout_template.dart index 88e796d..d16feb4 100644 --- a/src/lib/core/theme/auth_layout_template.dart +++ b/src/lib/core/theme/auth_layout_template.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'app_colors.dart'; /// The master layout template for all authentication screens. /// Handles the UI skeleton, loading states, backgrounds, and responsive scrolling. @@ -36,13 +35,16 @@ class AuthLayoutTemplate extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: AppColors.background, + backgroundColor: Theme.of(context).scaffoldBackgroundColor, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: Navigator.canPop(context) ? IconButton( - icon: const Icon(Icons.arrow_back, color: AppColors.primary), + icon: Icon( + Icons.arrow_back, + color: Theme.of(context).colorScheme.primary, + ), onPressed: () => Navigator.pop(context), ) : null, @@ -54,9 +56,11 @@ class AuthLayoutTemplate extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - _buildHeader(), + _buildHeader(context), const SizedBox(height: 32), - useCard ? _buildCardContainer() : _buildTransparentContainer(), + useCard + ? _buildCardContainer(context) + : _buildTransparentContainer(context), const SizedBox(height: 32), if (footerContent != null) footerContent!, ], @@ -67,7 +71,7 @@ class AuthLayoutTemplate extends StatelessWidget { ); } - Widget _buildHeader() { + Widget _buildHeader(BuildContext context) { return Column( children: [ customHeaderIcon ?? @@ -75,37 +79,41 @@ class AuthLayoutTemplate extends StatelessWidget { width: 80, height: 80, decoration: BoxDecoration( - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(24), boxShadow: [ BoxShadow( - color: AppColors.primary.withOpacity(0.1), + color: Theme.of(context).colorScheme.primary.withOpacity(0.1), blurRadius: 20, offset: const Offset(0, 10), ), ], ), - child: const Center( - child: Icon(Icons.task_alt, size: 48, color: AppColors.primary), + child: Center( + child: Icon( + Icons.task_alt, + size: 48, + color: Theme.of(context).colorScheme.primary, + ), ), ), const SizedBox(height: 24), Text( title, - style: const TextStyle( + style: TextStyle( fontSize: 28, fontWeight: FontWeight.w800, - color: AppColors.textDark, + color: Theme.of(context).colorScheme.onSurface, letterSpacing: -0.5, ), ), const SizedBox(height: 8), Text( subtitle, - style: const TextStyle( + style: TextStyle( fontSize: 14, fontWeight: FontWeight.w500, - color: AppColors.textSecondary, + color: Theme.of(context).colorScheme.onSurfaceVariant, ), textAlign: TextAlign.center, ), @@ -113,27 +121,28 @@ class AuthLayoutTemplate extends StatelessWidget { ); } - Widget _buildCardContainer() { + Widget _buildCardContainer(BuildContext context) { return Container( padding: const EdgeInsets.all(32), decoration: BoxDecoration( - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(32), boxShadow: [ BoxShadow( - color: AppColors.primary.withOpacity(0.08), + color: Theme.of(context).colorScheme.primary.withOpacity(0.08), blurRadius: 30, offset: const Offset(0, 10), ), ], ), - child: _buildFormElements(), + child: _buildFormElements(context), ); } - Widget _buildTransparentContainer() => _buildFormElements(); + Widget _buildTransparentContainer(BuildContext context) => + _buildFormElements(context); - Widget _buildFormElements() { + Widget _buildFormElements(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -143,8 +152,9 @@ class AuthLayoutTemplate extends StatelessWidget { // Disable button if loading onPressed: isLoading ? null : onSubmit, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primary, - disabledBackgroundColor: AppColors.primary.withOpacity(0.6), + backgroundColor: Theme.of(context).colorScheme.primary, + disabledBackgroundColor: + Theme.of(context).colorScheme.primary.withOpacity(0.6), padding: const EdgeInsets.symmetric(vertical: 20), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), @@ -152,11 +162,11 @@ class AuthLayoutTemplate extends StatelessWidget { elevation: isLoading ? 0 : 4, ), child: isLoading - ? const SizedBox( + ? SizedBox( height: 20, width: 20, child: CircularProgressIndicator( - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, strokeWidth: 2, ), ) @@ -165,16 +175,16 @@ class AuthLayoutTemplate extends StatelessWidget { children: [ Text( submitText, - style: const TextStyle( + style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, ), ), const SizedBox(width: 8), - const Icon( + Icon( Icons.arrow_forward, - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, size: 20, ), ], @@ -182,21 +192,21 @@ class AuthLayoutTemplate extends StatelessWidget { ), if (showSocial) ...[ const SizedBox(height: 32), - const Row( + Row( children: [ - Expanded(child: Divider(color: AppColors.border)), - Padding( + Expanded( + child: Divider(color: Theme.of(context).colorScheme.outline), + ), + const Padding( padding: EdgeInsets.symmetric(horizontal: 16), child: Text( 'OR', - style: TextStyle( - fontSize: 10, - fontWeight: FontWeight.bold, - color: AppColors.textSecondary, - ), + style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold), ), ), - Expanded(child: Divider(color: AppColors.border)), + Expanded( + child: Divider(color: Theme.of(context).colorScheme.outline), + ), ], ), const SizedBox(height: 24), diff --git a/src/lib/core/theme/custom_text_field.dart b/src/lib/core/theme/custom_text_field.dart index 7e98bcf..1f73215 100644 --- a/src/lib/core/theme/custom_text_field.dart +++ b/src/lib/core/theme/custom_text_field.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'app_colors.dart'; /// A highly reusable text input field component. class CustomTextField extends StatelessWidget { @@ -36,7 +35,7 @@ class CustomTextField extends StatelessWidget { style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, - color: AppColors.textDark.withOpacity(0.6), + color: Theme.of(context).colorScheme.onSurface.withOpacity(0.6), letterSpacing: 1, ), ), @@ -44,21 +43,21 @@ class CustomTextField extends StatelessWidget { TextFormField( controller: controller, obscureText: obscureText, - style: const TextStyle( - color: AppColors.textDark, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurface, fontWeight: FontWeight.w600, fontSize: 16, ), decoration: InputDecoration( hintText: hint, hintStyle: TextStyle( - color: AppColors.textDark.withOpacity(0.3), + color: Theme.of(context).colorScheme.onSurface.withOpacity(0.3), fontWeight: FontWeight.w400, fontSize: 16, ), filled: true, - fillColor: AppColors.inputBackground, - prefixIcon: Icon(icon, color: AppColors.primary), + fillColor: Theme.of(context).colorScheme.surface, + prefixIcon: Icon(icon, color: Theme.of(context).colorScheme.primary), suffixIcon: isPassword ? IconButton( icon: Icon( @@ -78,12 +77,12 @@ class CustomTextField extends StatelessWidget { ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(16), - borderSide: const BorderSide(color: AppColors.border), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(16), - borderSide: const BorderSide( - color: AppColors.primary, + borderSide: BorderSide( + color: Theme.of(context).colorScheme.primary, width: 2, ), ), diff --git a/src/lib/core/theme/theme_provider.dart b/src/lib/core/theme/theme_provider.dart new file mode 100644 index 0000000..d265fea --- /dev/null +++ b/src/lib/core/theme/theme_provider.dart @@ -0,0 +1,57 @@ +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class ThemeProvider extends ChangeNotifier { + + static const String _themeKey = "theme_mode"; + + ThemeMode _themeMode = ThemeMode.light; + + ThemeMode get themeMode => _themeMode; + + ThemeProvider() { + _loadThemeFromPrefs(); + } + + // func change theme + void updateTheme(String appearance) { + final normalized = appearance.trim().toLowerCase(); + + if (normalized == 'dark') { + _themeMode = ThemeMode.dark; + } else if (normalized == 'light') { + _themeMode = ThemeMode.light; + } else { + _themeMode = ThemeMode.system; + } + + _saveThemeToPrefs( + _themeMode == ThemeMode.dark + ? 'Dark' + : _themeMode == ThemeMode.light + ? 'Light' + : 'System', + ); + notifyListeners(); + } + + Future _saveThemeToPrefs(String appearance) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_themeKey, appearance); + } + + // load theme when user open app + Future _loadThemeFromPrefs() async { + final prefs = await SharedPreferences.getInstance(); + final appearance = (prefs.getString(_themeKey) ?? 'Light').trim().toLowerCase(); + + if (appearance == 'dark') { + _themeMode = ThemeMode.dark; + } else if (appearance == 'system') { + _themeMode = ThemeMode.system; + } else { + _themeMode = ThemeMode.light; + } + notifyListeners(); + } +} \ No newline at end of file diff --git a/src/lib/core/widgets/custom_input_field.dart b/src/lib/core/widgets/custom_input_field.dart index 29bb775..3552a50 100644 --- a/src/lib/core/widgets/custom_input_field.dart +++ b/src/lib/core/widgets/custom_input_field.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../theme/app_colors.dart'; class CustomInputField extends StatelessWidget { final String label; @@ -32,8 +31,11 @@ class CustomInputField extends StatelessWidget { contentPadding: EdgeInsets.zero, enabledBorder: const UnderlineInputBorder( borderSide: BorderSide(color: Colors.black26)), - focusedBorder: const UnderlineInputBorder( - borderSide: BorderSide(color: AppColors.primaryBlue)), + focusedBorder: UnderlineInputBorder( + borderSide: BorderSide( + color: Theme.of(context).colorScheme.primary, + ), + ), ), ), ], diff --git a/src/lib/features/auth/otp_verification_view.dart b/src/lib/features/auth/otp_verification_view.dart index 1f80d61..0f96ea4 100644 --- a/src/lib/features/auth/otp_verification_view.dart +++ b/src/lib/features/auth/otp_verification_view.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import '../../core/theme/app_colors.dart'; import '../auth/viewmodels/auth_viewmodels.dart'; import '../auth/presentation/view/new_password_view.dart'; @@ -18,18 +17,21 @@ class _OtpVerificationViewState extends State { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: AppColors.background, + backgroundColor: Theme.of(context).scaffoldBackgroundColor, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: IconButton( - icon: const Icon(Icons.arrow_back, color: AppColors.primary), + icon: Icon( + Icons.arrow_back, + color: Theme.of(context).colorScheme.primary, + ), onPressed: () => Navigator.pop(context), ), - title: const Text( + title: Text( 'OTP Verification', style: TextStyle( - color: AppColors.primary, + color: Theme.of(context).colorScheme.primary, fontWeight: FontWeight.bold, fontSize: 18, ), @@ -46,24 +48,26 @@ class _OtpVerificationViewState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Icon( + Icon( Icons.mark_email_read, size: 80, - color: AppColors.primary, + color: Theme.of(context).colorScheme.primary, ), const SizedBox(height: 32), - const Text( + Text( 'Enter 8-digit code', // Show correct 8-digit count style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, - color: AppColors.textDark, + color: Theme.of(context).colorScheme.onSurface, ), ), const SizedBox(height: 8), - const Text( + Text( 'The code has been sent to your email.', - style: TextStyle(color: AppColors.textSecondary), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), ), const SizedBox(height: 40), @@ -117,28 +121,28 @@ class _OtpVerificationViewState extends State { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(errorMessage), - backgroundColor: AppColors.error, + backgroundColor: Theme.of(context).colorScheme.error, ), ); } }, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primary, + backgroundColor: Theme.of(context).colorScheme.primary, minimumSize: const Size(double.infinity, 56), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), ), child: _vm.isLoading - ? const CircularProgressIndicator( - color: AppColors.white, + ? CircularProgressIndicator( + color: Theme.of(context).colorScheme.surface, ) - : const Text( + : Text( 'CONFIRM', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, ), ), ), @@ -154,24 +158,31 @@ class _OtpVerificationViewState extends State { if (errorMessage == null) { ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( + SnackBar( content: Text('OTP code resent!'), - backgroundColor: AppColors.success, + backgroundColor: Theme.of(context).colorScheme.tertiary, ), ); } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(errorMessage), - backgroundColor: AppColors.error, + backgroundColor: Theme.of(context).colorScheme.error, ), ); } }, - icon: const Icon(Icons.refresh, size: 18, color: AppColors.primary), - label: const Text( + icon: Icon( + Icons.refresh, + size: 18, + color: Theme.of(context).colorScheme.primary, + ), + label: Text( 'Resend code', - style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold), + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), ), ) ], @@ -190,9 +201,9 @@ class _OtpVerificationViewState extends State { width: boxWidth, // Use calculated width height: 48, decoration: BoxDecoration( - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(8), - border: Border.all(color: AppColors.border), + border: Border.all(color: Theme.of(context).colorScheme.outline), ), child: TextField( onChanged: (value) { @@ -205,10 +216,10 @@ class _OtpVerificationViewState extends State { FocusScope.of(context).previousFocus(); } }, - style: const TextStyle( + style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, - color: AppColors.textDark, + color: Theme.of(context).colorScheme.onSurface, ), keyboardType: TextInputType.number, textAlign: TextAlign.center, diff --git a/src/lib/features/auth/presentation/view/forgot_password_view.dart b/src/lib/features/auth/presentation/view/forgot_password_view.dart index bc105ca..833b0a8 100644 --- a/src/lib/features/auth/presentation/view/forgot_password_view.dart +++ b/src/lib/features/auth/presentation/view/forgot_password_view.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/theme/auth_layout_template.dart'; import '../../../../core/theme/custom_text_field.dart'; import '../viewmodels/auth_viewmodels.dart'; @@ -26,12 +25,16 @@ class _ForgotPasswordViewState extends State { isLoading: _vm.isLoading, customHeaderIcon: Container( width: 120, height: 120, - decoration: const BoxDecoration( - color: AppColors.white, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, shape: BoxShape.circle, - boxShadow: [BoxShadow(color: Color(0xFFD1D9E6), blurRadius: 16)], + boxShadow: const [BoxShadow(color: Color(0xFFD1D9E6), blurRadius: 16)], + ), + child: Icon( + Icons.lock_reset, + size: 64, + color: Theme.of(context).colorScheme.primary, ), - child: const Icon(Icons.lock_reset, size: 64, color: AppColors.primary), ), onSubmit: () async { FocusScope.of(context).unfocus(); // Đóng bàn phím @@ -45,7 +48,12 @@ class _ForgotPasswordViewState extends State { Navigator.push(context, MaterialPageRoute(builder: (_) => const OtpVerificationView())); } else { // Có lỗi (như nhập sai định dạng, spam nút) -> Vã cái lỗi màu đỏ ra - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, formContent: CustomTextField( @@ -54,14 +62,25 @@ class _ForgotPasswordViewState extends State { icon: Icons.mail, controller: _vm.emailCtrl, ), - footerContent: const Padding( + footerContent: Padding( padding: EdgeInsets.only(bottom: 24.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - Icon(Icons.help, size: 16, color: AppColors.primary), - SizedBox(width: 4), - Text('Cần hỗ trợ? Liên hệ CSKH', style: TextStyle(color: AppColors.textSecondary, fontSize: 14, fontWeight: FontWeight.bold)), + Icon( + Icons.help, + size: 16, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 4), + Text( + 'Cần hỗ trợ? Liên hệ CSKH', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 14, + fontWeight: FontWeight.bold, + ), + ), ], ), ), diff --git a/src/lib/features/auth/presentation/view/login_view.dart b/src/lib/features/auth/presentation/view/login_view.dart index 8d39494..7807b4f 100644 --- a/src/lib/features/auth/presentation/view/login_view.dart +++ b/src/lib/features/auth/presentation/view/login_view.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/theme/auth_layout_template.dart'; import '../../../../core/theme/custom_text_field.dart'; import '../viewmodels/auth_viewmodels.dart'; @@ -28,13 +27,23 @@ class _LoginViewState extends State { onGoogleTap: () async { final error = await _vm.loginWithGoogle(); if (error != null && context.mounted) { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(error), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(error), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, onFacebookTap: () async { final error = await _vm.loginWithFacebook(); if (error != null && context.mounted) { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(error), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(error), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, onSubmit: () async { @@ -43,11 +52,21 @@ class _LoginViewState extends State { if (!context.mounted) return; if (errorMessage == null) { - ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Đăng nhập thành công!'), backgroundColor: AppColors.success)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: const Text('Đăng nhập thành công!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), + ); // If LoginView was pushed on top of AuthGate, pop back to root so MainScreen is visible. Navigator.of(context).popUntil((route) => route.isFirst); } else { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, formContent: Column( @@ -60,28 +79,57 @@ class _LoginViewState extends State { ), TextButton( onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const ForgotPasswordView())), - child: const Text('Quên mật khẩu?', style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold)), + child: Text( + 'Quên mật khẩu?', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), ), ], ), - footerContent: _buildFooter('Chưa có tài khoản? ', 'Đăng ký ngay', () { + footerContent: _buildFooter( + context, + 'Chưa có tài khoản? ', + 'Đăng ký ngay', + () { Navigator.push(context, MaterialPageRoute(builder: (_) => const RegisterView())); - }), + }, + ), ), ); } - Widget _buildFooter(String text, String action, VoidCallback onTap) { + Widget _buildFooter( + BuildContext context, + String text, + String action, + VoidCallback onTap, + ) { return Padding( padding: const EdgeInsets.only(bottom: 24.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text(text, style: const TextStyle(color: AppColors.textSecondary, fontSize: 16)), + Text( + text, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 16, + ), + ), TextButton( onPressed: onTap, style: TextButton.styleFrom(minimumSize: const Size(50, 48)), - child: Text(action, style: const TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold, fontSize: 16)), + child: Text( + action, + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), ), ], ), diff --git a/src/lib/features/auth/presentation/view/new_password_view.dart b/src/lib/features/auth/presentation/view/new_password_view.dart index dbe9bfc..31e50d1 100644 --- a/src/lib/features/auth/presentation/view/new_password_view.dart +++ b/src/lib/features/auth/presentation/view/new_password_view.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/theme/auth_layout_template.dart'; import '../../../../core/theme/custom_text_field.dart'; import '../viewmodels/auth_viewmodels.dart'; @@ -23,10 +22,14 @@ class _NewPasswordViewState extends State { subtitle: 'Mật khẩu mới phải khác với mật khẩu cũ', submitText: 'Cập nhật', isLoading: _vm.isLoading, - customHeaderIcon: const CircleAvatar( + customHeaderIcon: CircleAvatar( radius: 40, backgroundColor: Color(0xFFEBF2FF), - child: Icon(Icons.lock_reset, size: 40, color: AppColors.primary), + child: Icon( + Icons.lock_reset, + size: 40, + color: Theme.of(context).colorScheme.primary, + ), ), onSubmit: () async { FocusScope.of(context).unfocus(); @@ -37,12 +40,22 @@ class _NewPasswordViewState extends State { if (errorMessage == null) { // Null -> Thành công -> Báo xanh mướt - ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Đổi mật khẩu thành công!'), backgroundColor: AppColors.success)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: const Text('Đổi mật khẩu thành công!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), + ); // Cú đá chót: Xóa hết lịch sử trang, đá thẳng mặt về trang Login (isFirst) Navigator.popUntil(context, (route) => route.isFirst); } else { // Nếu lỗi do User nhập lệch pass -> Chửi - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, formContent: Column( @@ -62,12 +75,22 @@ class _NewPasswordViewState extends State { color: const Color(0xFFEBF2FF), borderRadius: BorderRadius.circular(12), ), - child: const Row( + child: Row( children: [ - Icon(Icons.info, color: AppColors.primary, size: 16), - SizedBox(width: 8), + Icon( + Icons.info, + color: Theme.of(context).colorScheme.primary, + size: 16, + ), + const SizedBox(width: 8), Expanded( - child: Text('Mật khẩu tối thiểu 6 ký tự để đảm bảo an toàn.', style: TextStyle(fontSize: 12, color: AppColors.primary)), + child: Text( + 'Mật khẩu tối thiểu 6 ký tự để đảm bảo an toàn.', + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.primary, + ), + ), ), ], ), diff --git a/src/lib/features/auth/presentation/view/otp_verification_view.dart b/src/lib/features/auth/presentation/view/otp_verification_view.dart index b8bb7b7..bdf3e77 100644 --- a/src/lib/features/auth/presentation/view/otp_verification_view.dart +++ b/src/lib/features/auth/presentation/view/otp_verification_view.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import '../../../../core/theme/app_colors.dart'; import '../viewmodels/auth_viewmodels.dart'; import 'new_password_view.dart'; @@ -16,17 +15,24 @@ class _OtpVerificationViewState extends State { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: AppColors.background, + backgroundColor: Theme.of(context).scaffoldBackgroundColor, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: IconButton( - icon: const Icon(Icons.arrow_back, color: AppColors.primary), + icon: Icon( + Icons.arrow_back, + color: Theme.of(context).colorScheme.primary, + ), onPressed: () => Navigator.pop(context), ), - title: const Text( + title: Text( 'Xác thực OTP', - style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold, fontSize: 18), + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + fontSize: 18, + ), ), centerTitle: true, ), @@ -39,16 +45,26 @@ class _OtpVerificationViewState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Icon(Icons.mark_email_read, size: 80, color: AppColors.primary), + Icon( + Icons.mark_email_read, + size: 80, + color: Theme.of(context).colorScheme.primary, + ), const SizedBox(height: 32), - const Text( + Text( 'Nhập mã 8 số', // Sửa chữ thành 8 số - style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: AppColors.textDark), + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), ), const SizedBox(height: 8), - const Text( + Text( 'Mã đã được gửi đến email của bạn.', - style: TextStyle(color: AppColors.textSecondary), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), ), const SizedBox(height: 40), @@ -73,20 +89,29 @@ class _OtpVerificationViewState extends State { ); } else { ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error), + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), ); } }, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primary, + backgroundColor: Theme.of(context).colorScheme.primary, minimumSize: const Size(double.infinity, 56), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), ), child: _vm.isLoading - ? const CircularProgressIndicator(color: AppColors.white) - : const Text( + ? CircularProgressIndicator( + color: Theme.of(context).colorScheme.surface, + ) + : Text( 'XÁC NHẬN', - style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: AppColors.white), + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.surface, + ), ), ), const SizedBox(height: 16), @@ -98,18 +123,31 @@ class _OtpVerificationViewState extends State { if (errorMessage == null) { ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Đã gửi lại mã OTP!'), backgroundColor: AppColors.success), + SnackBar( + content: const Text('Đã gửi lại mã OTP!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), ); } else { ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error), + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), ); } }, - icon: const Icon(Icons.refresh, size: 18, color: AppColors.primary), - label: const Text( + icon: Icon( + Icons.refresh, + size: 18, + color: Theme.of(context).colorScheme.primary, + ), + label: Text( 'Gửi lại mã', - style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold), + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), ), ) ], @@ -125,9 +163,9 @@ class _OtpVerificationViewState extends State { return Container( width: 35, height: 48, // Thu nhỏ kích thước ô lại để nhét vừa 8 ô trên 1 dòng decoration: BoxDecoration( - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(8), - border: Border.all(color: AppColors.border), + border: Border.all(color: Theme.of(context).colorScheme.outline), ), child: TextField( onChanged: (value) { @@ -137,7 +175,11 @@ class _OtpVerificationViewState extends State { if (value.isNotEmpty && index < 7) FocusScope.of(context).nextFocus(); if (value.isEmpty && index > 0) FocusScope.of(context).previousFocus(); }, - style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: AppColors.textDark), + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), keyboardType: TextInputType.number, textAlign: TextAlign.center, inputFormatters: [ diff --git a/src/lib/features/auth/presentation/view/register_view.dart b/src/lib/features/auth/presentation/view/register_view.dart index 17dfc88..ddc3556 100644 --- a/src/lib/features/auth/presentation/view/register_view.dart +++ b/src/lib/features/auth/presentation/view/register_view.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; +import 'package:task_management_app/features/auth/presentation/view/login_view.dart'; import '../../../../core/theme/auth_layout_template.dart'; import '../../../../core/theme/custom_text_field.dart'; import '../viewmodels/auth_viewmodels.dart'; @@ -29,11 +29,21 @@ class _RegisterViewState extends State { if (!context.mounted) return; if (errorMessage == null) { - ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Đăng ký thành công!'), backgroundColor: AppColors.success)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: const Text('Đăng ký thành công!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), + ); // Return to the existing LoginView to avoid stacking duplicate login routes. Navigator.pop(context); } else { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, formContent: Column( @@ -55,11 +65,24 @@ class _RegisterViewState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Text('Đã có tài khoản? ', style: TextStyle(color: AppColors.textSecondary, fontSize: 16)), + Text( + 'Đã có tài khoản? ', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 16, + ), + ), TextButton( onPressed: () => Navigator.pop(context), style: TextButton.styleFrom(minimumSize: const Size(50, 48)), - child: const Text('Đăng nhập', style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold, fontSize: 16)), + child: Text( + 'Đăng nhập', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), ), ], ), diff --git a/src/lib/features/main/view/screens/main_screen.dart b/src/lib/features/main/view/screens/main_screen.dart index 033f2bf..77e3308 100644 --- a/src/lib/features/main/view/screens/main_screen.dart +++ b/src/lib/features/main/view/screens/main_screen.dart @@ -3,7 +3,6 @@ import 'package:task_management_app/features/statistics/viewmodel/statistics_vie import 'package:task_management_app/features/tasks/view/screens/home_screen.dart'; import 'settings_screen.dart'; import 'package:task_management_app/features/user/viewmodel/user_profile_viewmodel.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../note/view/focus_screen.dart'; import '../../../note/viewmodel/focus_viewmodel.dart'; import '../../../statistics/view/screens/statistics_screen.dart'; @@ -59,11 +58,11 @@ class _MainScreenState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ - _buildNavItem(Icons.checklist_rounded, 'Công việc', 0), - _buildNavItem(Icons.calendar_today_rounded, 'Lịch', 1), - _buildNavItem(Icons.timer_rounded, 'Tập trung', 2), - _buildNavItem(Icons.bar_chart_rounded, 'Thống kê', 3), - _buildNavItem(Icons.person_2_rounded, 'Cá nhân', 4), + _buildNavItem(context, Icons.checklist_rounded, 'Công việc', 0), + _buildNavItem(context, Icons.calendar_today_rounded, 'Lịch', 1), + _buildNavItem(context, Icons.timer_rounded, 'Tập trung', 2), + _buildNavItem(context, Icons.bar_chart_rounded, 'Thống kê', 3), + _buildNavItem(context, Icons.person_2_rounded, 'Cá nhân', 4), ], ), ), @@ -71,7 +70,7 @@ class _MainScreenState extends State { ); } - Widget _buildNavItem(IconData icon, String label, int index) { + Widget _buildNavItem(BuildContext context, IconData icon, String label, int index) { bool isSelected = _currentIndex == index; return GestureDetector( @@ -87,14 +86,22 @@ class _MainScreenState extends State { child: Column( mainAxisSize: MainAxisSize.min, children: [ - Icon(icon, color: isSelected ? AppColors.primaryBlue : AppColors.grayText, size: 24), + Icon( + icon, + color: isSelected + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.onSurfaceVariant, + size: 24, + ), const SizedBox(height: 4), Text( label, style: TextStyle( fontSize: 10, fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, - color: isSelected ? AppColors.primaryBlue : AppColors.grayText, + color: isSelected + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.onSurfaceVariant, ), ) ], diff --git a/src/lib/features/note/view/focus_screen.dart b/src/lib/features/note/view/focus_screen.dart index 9349b49..b487ace 100644 --- a/src/lib/features/note/view/focus_screen.dart +++ b/src/lib/features/note/view/focus_screen.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; import '../viewmodel/focus_viewmodel.dart'; import '../view/focus_widget.dart'; @@ -35,10 +34,23 @@ class FocusScreen extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text('Pomodoro', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), - Text('${currentPomodoro.toInt()} phút', style: const TextStyle(color: AppColors.primaryBlue, fontWeight: FontWeight.bold)), + Text( + '${currentPomodoro.toInt()} phút', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), ], ), - Slider(value: currentPomodoro, min: 5, max: 60, divisions: 55, activeColor: AppColors.primaryBlue, onChanged: (val) => setStateDialog(() => currentPomodoro = val)), + Slider( + value: currentPomodoro, + min: 5, + max: 60, + divisions: 55, + activeColor: Theme.of(context).colorScheme.primary, + onChanged: (val) => setStateDialog(() => currentPomodoro = val), + ), const SizedBox(height: 5), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, @@ -53,7 +65,9 @@ class FocusScreen extends StatelessWidget { // --- Hardware Settings --- SwitchListTile( title: const Text('Rung', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), - value: currentVibrate, activeColor: AppColors.primaryBlue, contentPadding: EdgeInsets.zero, + value: currentVibrate, + activeColor: Theme.of(context).colorScheme.primary, + contentPadding: EdgeInsets.zero, onChanged: (val) => setStateDialog(() => currentVibrate = val), ), const SizedBox(height: 10), @@ -88,7 +102,10 @@ class FocusScreen extends StatelessWidget { vm.updateSettings(newPomodoroMinutes: currentPomodoro.toInt(), newBreakMinutes: currentBreak.toInt(), vibrate: currentVibrate, ringtone: currentRingtone); Navigator.pop(context); }, - style: ElevatedButton.styleFrom(backgroundColor: AppColors.primaryBlue, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10))), + style: ElevatedButton.styleFrom( + backgroundColor: Theme.of(context).colorScheme.primary, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + ), child: const Text('Lưu', style: TextStyle(color: Colors.white)), ), ], @@ -102,7 +119,7 @@ class FocusScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: const Color(0xFFF4F6F9), + backgroundColor: Theme.of(context).scaffoldBackgroundColor, body: SafeArea( child: SingleChildScrollView( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), @@ -123,7 +140,17 @@ class FocusScreen extends StatelessWidget { // Settings Icon GestureDetector( onTap: () => _showSettingsDialog(context), - child: Container(padding: const EdgeInsets.all(10), decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), child: const Icon(Icons.settings_outlined, color: AppColors.primaryBlue)), + child: Container( + padding: const EdgeInsets.all(10), + decoration: const BoxDecoration( + color: Colors.white, + shape: BoxShape.circle, + ), + child: Icon( + Icons.settings_outlined, + color: Theme.of(context).colorScheme.primary, + ), + ), ), ], ), diff --git a/src/lib/features/note/view/focus_widget.dart b/src/lib/features/note/view/focus_widget.dart index 8037b4a..e676057 100644 --- a/src/lib/features/note/view/focus_widget.dart +++ b/src/lib/features/note/view/focus_widget.dart @@ -1,7 +1,6 @@ import 'dart:io'; // Import to display image files import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; import '../viewmodel/focus_viewmodel.dart'; // --- Tab Selector Widget --- @@ -22,27 +21,46 @@ class FocusTabSelector extends StatelessWidget { child: Row( mainAxisSize: MainAxisSize.min, children: [ - _buildTabBtn('Pomodoro', vm.isPomodoroMode, () => vm.setMode(true)), - _buildTabBtn('Nghỉ ngắn', !vm.isPomodoroMode, () => vm.setMode(false)), + _buildTabBtn( + context, + 'Pomodoro', + vm.isPomodoroMode, + () => vm.setMode(true), + ), + _buildTabBtn( + context, + 'Nghỉ ngắn', + !vm.isPomodoroMode, + () => vm.setMode(false), + ), ], ), ); } - Widget _buildTabBtn(String label, bool isSelected, VoidCallback onTap) { + Widget _buildTabBtn( + BuildContext context, + String label, + bool isSelected, + VoidCallback onTap, + ) { return GestureDetector( onTap: onTap, child: AnimatedContainer( duration: const Duration(milliseconds: 200), padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 10), decoration: BoxDecoration( - color: isSelected ? AppColors.primaryBlue : Colors.transparent, + color: isSelected + ? Theme.of(context).colorScheme.primary + : Colors.transparent, borderRadius: BorderRadius.circular(15), ), child: Text( label, style: TextStyle( - color: isSelected ? Colors.white : const Color(0xFF757575), + color: isSelected + ? Colors.white + : Theme.of(context).colorScheme.onSurfaceVariant, fontWeight: FontWeight.bold, fontSize: 14, ), @@ -73,7 +91,7 @@ class TimerDisplayWidget extends StatelessWidget { child: CircularProgressIndicator( value: vm.progress, strokeWidth: 14, - color: AppColors.primaryBlue, + color: Theme.of(context).colorScheme.primary, backgroundColor: Colors.transparent, strokeCap: StrokeCap.round, ), @@ -96,7 +114,12 @@ class TimerDisplayWidget extends StatelessWidget { const SizedBox(height: 4), Text( vm.isPomodoroMode ? 'TẬP TRUNG' : 'NGHỈ NGƠI', - style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: AppColors.primaryBlue.withOpacity(0.8), letterSpacing: 2), + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.primary.withOpacity(0.8), + letterSpacing: 2, + ), ), ], ), @@ -130,7 +153,9 @@ class TimerControlsWidget extends StatelessWidget { icon: vm.isRinging ? Icons.notifications_off_rounded // Muted bell icon : (vm.isRunning ? Icons.pause_rounded : Icons.play_arrow_rounded), - bgColor: vm.isRinging ? Colors.redAccent : AppColors.primaryBlue, + bgColor: vm.isRinging + ? Colors.redAccent + : Theme.of(context).colorScheme.primary, iconColor: Colors.white, size: 85, hasShadow: true, @@ -197,9 +222,16 @@ class QuickNoteCard extends StatelessWidget { children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: const [ - Text('Ghi chú nhanh', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), - Text('Đang thực hiện', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: AppColors.grayText)), + children: [ + const Text('Ghi chú nhanh', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + Text( + 'Đang thực hiện', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), const SizedBox(height: 15), @@ -282,7 +314,11 @@ class QuickNoteCard extends StatelessWidget { // IMAGE PICKER BUTTON GestureDetector( onTap: () => vm.pickImage(), - child: Icon(Icons.image_outlined, color: AppColors.primaryBlue, size: 22), + child: Icon( + Icons.image_outlined, + color: Theme.of(context).colorScheme.primary, + size: 22, + ), ), ], ), @@ -292,7 +328,7 @@ class QuickNoteCard extends StatelessWidget { context.read().addNote(); }, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primaryBlue, + backgroundColor: Theme.of(context).colorScheme.primary, padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), elevation: 0, @@ -329,7 +365,13 @@ class QuickNoteCard extends StatelessWidget { margin: const EdgeInsets.only(top: 2, right: 12), width: 22, height: 22, - decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue, width: 2)), + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: Theme.of(context).colorScheme.primary, + width: 2, + ), + ), ), ), // CONTENT (TEXT AND IMAGE) diff --git a/src/lib/features/statistics/view/screens/statistics_screen.dart b/src/lib/features/statistics/view/screens/statistics_screen.dart index b8eb2b9..abdf952 100644 --- a/src/lib/features/statistics/view/screens/statistics_screen.dart +++ b/src/lib/features/statistics/view/screens/statistics_screen.dart @@ -1,7 +1,6 @@ import 'package:flutter/material.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../viewmodel/statistics_viewmodel.dart'; import '../widgets/statistics_widgets.dart'; @@ -29,9 +28,13 @@ class _StatisticsScreenState extends State { } - Icon _getIconForCategory(String category) { + Icon _getIconForCategory(BuildContext context, String category) { switch (category) { - case 'Design': return const Icon(Icons.checklist_rtl_rounded, color: AppColors.primaryBlue); + case 'Design': + return Icon( + Icons.checklist_rtl_rounded, + color: Theme.of(context).colorScheme.primary, + ); case 'Research': return const Icon(Icons.timer_outlined, color: Color(0xFFE67E22)); case 'Development': return const Icon(Icons.calendar_month_outlined, color: Color(0xFF9B59B6)); default: return const Icon(Icons.task_alt_rounded, color: Colors.green); @@ -41,7 +44,7 @@ class _StatisticsScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: const Color(0xFFF4F6F9), + backgroundColor: Theme.of(context).scaffoldBackgroundColor, body: Consumer( builder: (context, viewModel, child) { @@ -86,7 +89,10 @@ class _StatisticsScreenState extends State { Container( padding: const EdgeInsets.all(10), decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), - child: const Icon(Icons.notifications_none_rounded, color: AppColors.primaryBlue), + child: Icon( + Icons.notifications_none_rounded, + color: Theme.of(context).colorScheme.primary, + ), ) ], ), @@ -118,7 +124,14 @@ class _StatisticsScreenState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text('Hoàn thành gần đây', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), - Text('Xem tất cả', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: AppColors.primaryBlue)), + Text( + 'Xem tất cả', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.primary, + ), + ), ], ), const SizedBox(height: 15), diff --git a/src/lib/features/statistics/view/widgets/statistics_widgets.dart b/src/lib/features/statistics/view/widgets/statistics_widgets.dart index a93344e..7ff72cd 100644 --- a/src/lib/features/statistics/view/widgets/statistics_widgets.dart +++ b/src/lib/features/statistics/view/widgets/statistics_widgets.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:task_management_app/features/statistics/model/StatisticsModel.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../tasks/model/task_model.dart'; import '../../../tasks/view/screens/task_detail_screen.dart'; @@ -21,7 +20,14 @@ class DailyProgressCard extends StatelessWidget { ), child: Column( children: [ - const Text('Tiến độ hôm nay', style: TextStyle(color: AppColors.grayText, fontSize: 16, fontWeight: FontWeight.w600)), + Text( + 'Tiến độ hôm nay', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), const SizedBox(height: 20), SizedBox( height: 140, @@ -32,8 +38,11 @@ class DailyProgressCard extends StatelessWidget { CircularProgressIndicator( value: (total > 0) ? percentage / 100 : 0, strokeWidth: 12, - backgroundColor: AppColors.backgroundBlue, - valueColor: AlwaysStoppedAnimation(AppColors.primaryBlue), + backgroundColor: + Theme.of(context).colorScheme.surfaceContainerHighest, + valueColor: AlwaysStoppedAnimation( + Theme.of(context).colorScheme.primary, + ), ), Column( mainAxisAlignment: MainAxisAlignment.center, @@ -52,7 +61,13 @@ class DailyProgressCard extends StatelessWidget { style: const TextStyle(fontSize: 16, color: Colors.black87), children: [ const TextSpan(text: 'Tuyệt vời! Bạn đã hoàn thành '), - TextSpan(text: '${percentage.toInt()}%', style: const TextStyle(color: AppColors.primaryBlue, fontWeight: FontWeight.bold)), + TextSpan( + text: '${percentage.toInt()}%', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), const TextSpan(text: '\nmục tiêu.'), ], ), @@ -105,7 +120,14 @@ class WeeklyChartCard extends StatelessWidget { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - const Text('Tuần này', style: TextStyle(color: AppColors.grayText, fontSize: 14, fontWeight: FontWeight.w600)), + Text( + 'Tuần này', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), const SizedBox(height: 5), Text('$thisWeekTotal Tasks', style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), ], @@ -123,13 +145,13 @@ class WeeklyChartCard extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.end, children: [ - _buildBar('T2', weeklyHeights.length > 0 ? weeklyHeights[0] : 0.1, 0), - _buildBar('T3', weeklyHeights.length > 1 ? weeklyHeights[1] : 0.1, 1), - _buildBar('T4', weeklyHeights.length > 2 ? weeklyHeights[2] : 0.1, 2), - _buildBar('T5', weeklyHeights.length > 3 ? weeklyHeights[3] : 0.1, 3), - _buildBar('T6', weeklyHeights.length > 4 ? weeklyHeights[4] : 0.1, 4), - _buildBar('T7', weeklyHeights.length > 5 ? weeklyHeights[5] : 0.1, 5), - _buildBar('CN', weeklyHeights.length > 6 ? weeklyHeights[6] : 0.1, 6), + _buildBar(context, 'T2', weeklyHeights.length > 0 ? weeklyHeights[0] : 0.1, 0), + _buildBar(context, 'T3', weeklyHeights.length > 1 ? weeklyHeights[1] : 0.1, 1), + _buildBar(context, 'T4', weeklyHeights.length > 2 ? weeklyHeights[2] : 0.1, 2), + _buildBar(context, 'T5', weeklyHeights.length > 3 ? weeklyHeights[3] : 0.1, 3), + _buildBar(context, 'T6', weeklyHeights.length > 4 ? weeklyHeights[4] : 0.1, 4), + _buildBar(context, 'T7', weeklyHeights.length > 5 ? weeklyHeights[5] : 0.1, 5), + _buildBar(context, 'CN', weeklyHeights.length > 6 ? weeklyHeights[6] : 0.1, 6), ], ), ], @@ -137,7 +159,7 @@ class WeeklyChartCard extends StatelessWidget { ); } - Widget _buildBar(String label, double heightRatio, int index) { + Widget _buildBar(BuildContext context, String label, double heightRatio, int index) { bool isActive = index == selectedIndex; return GestureDetector( onTap: () => onDaySelected(index), @@ -149,12 +171,23 @@ class WeeklyChartCard extends StatelessWidget { width: 35, height: 100 * (heightRatio > 0 ? heightRatio : 0.1), // Tối thiểu 10% để cột không bị "biến mất" decoration: BoxDecoration( - color: isActive ? AppColors.primaryBlue : const Color(0xFFF5F7FA), + color: isActive + ? Theme.of(context).colorScheme.primary + : const Color(0xFFF5F7FA), borderRadius: BorderRadius.circular(8), ), ), const SizedBox(height: 10), - Text(label, style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: isActive ? AppColors.primaryBlue : AppColors.grayText)), + Text( + label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: isActive + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), ); diff --git a/src/lib/features/tasks/view/screens/create_task_screen.dart b/src/lib/features/tasks/view/screens/create_task_screen.dart index a7f22c9..897153b 100644 --- a/src/lib/features/tasks/view/screens/create_task_screen.dart +++ b/src/lib/features/tasks/view/screens/create_task_screen.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/widgets/custom_input_field.dart'; import '../widgets/task_widgets.dart'; @@ -78,8 +77,13 @@ class _CreateTaskScreenState extends State { selected: isSelected, onSelected: (selected) => setState(() => _selectedCategoryIndex = selected ? index : 0), backgroundColor: const Color(0xFFF1F7FD), - selectedColor: AppColors.primaryBlue, - labelStyle: TextStyle(color: isSelected ? Colors.white : AppColors.primaryBlue, fontSize: 14), + selectedColor: Theme.of(context).colorScheme.primary, + labelStyle: TextStyle( + color: isSelected + ? Colors.white + : Theme.of(context).colorScheme.primary, + fontSize: 14, + ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), side: const BorderSide(color: Color(0xFFF1F7FD), width: 1)), @@ -118,7 +122,10 @@ class _CreateTaskScreenState extends State { ), Container( padding: const EdgeInsets.all(12), - decoration: BoxDecoration(color: AppColors.primaryBlue, borderRadius: BorderRadius.circular(15)), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primary, + borderRadius: BorderRadius.circular(15), + ), child: const Icon(Icons.date_range_rounded, color: Colors.white), ) ], @@ -156,7 +163,7 @@ class _CreateTaskScreenState extends State { child: ElevatedButton( onPressed: () {}, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primaryBlue, + backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(horizontal: 100, vertical: 15), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), diff --git a/src/lib/features/tasks/view/screens/home_screen.dart b/src/lib/features/tasks/view/screens/home_screen.dart index c30697a..62c6623 100644 --- a/src/lib/features/tasks/view/screens/home_screen.dart +++ b/src/lib/features/tasks/view/screens/home_screen.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../model/task_model.dart'; import '../widgets/task_widgets.dart'; import 'create_task_screen.dart'; @@ -39,7 +38,10 @@ class HomeScreen extends StatelessWidget { children: [ Positioned( top: 0, left: 0, right: 0, height: 250, - child: ClipPath(clipper: TopWaveClipper(), child: Container(color: AppColors.primaryBlue)), + child: ClipPath( + clipper: TopWaveClipper(), + child: Container(color: Theme.of(context).colorScheme.primary), + ), ), SafeArea( child: Column( @@ -85,7 +87,13 @@ class HomeScreen extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Today', style: Theme.of(context).textTheme.titleMedium), - Text(formattedDate, style: const TextStyle(color: AppColors.grayText, fontSize: 14)), + Text( + formattedDate, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 14, + ), + ), ], ), const SizedBox(height: 20), @@ -122,7 +130,11 @@ class HomeScreen extends StatelessWidget { child: Container( padding: const EdgeInsets.all(4), decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), - child: const Icon(Icons.add_rounded, size: 20, color: AppColors.primaryBlue), + child: Icon( + Icons.add_rounded, + size: 20, + color: Theme.of(context).colorScheme.primary, + ), ), ) ], @@ -133,7 +145,10 @@ class HomeScreen extends StatelessWidget { leading: Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration(color: const Color(0xFFF1F7FD), borderRadius: BorderRadius.circular(15)), - child: const Icon(Icons.call_outlined, color: AppColors.primaryBlue), + child: Icon( + Icons.call_outlined, + color: Theme.of(context).colorScheme.primary, + ), ), ), // ---------------------------------------- diff --git a/src/lib/features/tasks/view/screens/task_detail_screen.dart b/src/lib/features/tasks/view/screens/task_detail_screen.dart index 6297293..b4dc17b 100644 --- a/src/lib/features/tasks/view/screens/task_detail_screen.dart +++ b/src/lib/features/tasks/view/screens/task_detail_screen.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/widgets/custom_input_field.dart'; import '../../model/task_model.dart'; import '../widgets/task_widgets.dart'; // Contains TimePickerWidget @@ -67,7 +66,7 @@ class _TaskDetailScreenState extends State { List categories = ['Development', 'Research', 'Design', 'Backend']; return Scaffold( - backgroundColor: AppColors.backgroundBlue, + backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, @@ -121,8 +120,13 @@ class _TaskDetailScreenState extends State { if (selected) setState(() => _currentCategory = categories[index]); }, backgroundColor: const Color(0xFFF1F7FD), - selectedColor: AppColors.primaryBlue, - labelStyle: TextStyle(color: isSelected ? Colors.white : AppColors.primaryBlue, fontSize: 14), + selectedColor: Theme.of(context).colorScheme.primary, + labelStyle: TextStyle( + color: isSelected + ? Colors.white + : Theme.of(context).colorScheme.primary, + fontSize: 14, + ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), side: const BorderSide(color: Color(0xFFF1F7FD), width: 1)), @@ -177,7 +181,7 @@ class _TaskDetailScreenState extends State { child: ElevatedButton( onPressed: _saveChanges, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primaryBlue, + backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 15), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), diff --git a/src/lib/features/tasks/view/widgets/task_widgets.dart b/src/lib/features/tasks/view/widgets/task_widgets.dart index 20b453b..9b1cc75 100644 --- a/src/lib/features/tasks/view/widgets/task_widgets.dart +++ b/src/lib/features/tasks/view/widgets/task_widgets.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../model/task_model.dart'; import '../screens/task_detail_screen.dart'; @@ -44,7 +43,9 @@ class DateBox extends StatelessWidget { width: 55, margin: const EdgeInsets.only(right: 15), decoration: BoxDecoration( - color: isSelected ? AppColors.primaryBlue : Colors.white, + color: isSelected + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(20), border: Border.all(color: Colors.grey.shade300, width: 1), ), @@ -60,7 +61,9 @@ class DateBox extends StatelessWidget { Text(weekday, style: TextStyle( fontSize: 12, - color: isSelected ? AppColors.textLightBlue : AppColors.grayText)), + color: isSelected + ? Theme.of(context).colorScheme.secondary + : Theme.of(context).colorScheme.onSurfaceVariant)), ], ), ); @@ -105,7 +108,7 @@ class TaskCard extends StatelessWidget { child: Container( margin: const EdgeInsets.only(bottom: 20), decoration: BoxDecoration( - color: AppColors.taskCardBg, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(25), boxShadow: [ BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 10, offset: const Offset(0, 5)) @@ -116,8 +119,8 @@ class TaskCard extends StatelessWidget { Positioned( left: 0, top: 25, bottom: 25, width: 4, child: Container( - decoration: const BoxDecoration( - color: AppColors.primaryBlue, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primary, borderRadius: BorderRadius.only(topRight: Radius.circular(5), bottomRight: Radius.circular(5))), ), ), @@ -139,7 +142,10 @@ class TaskCard extends StatelessWidget { ), Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), - decoration: BoxDecoration(color: AppColors.timeBoxBg, borderRadius: BorderRadius.circular(10)), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.secondary, + borderRadius: BorderRadius.circular(10), + ), child: Text(timeString, style: const TextStyle(color: Colors.white, fontSize: 12)), ), ], @@ -183,8 +189,11 @@ class TimePickerWidget extends StatelessWidget { style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold)), const SizedBox(width: 5), - const Icon(Icons.keyboard_arrow_down_rounded, - color: AppColors.primaryBlue, size: 20) + Icon( + Icons.keyboard_arrow_down_rounded, + color: Theme.of(context).colorScheme.primary, + size: 20, + ) ], ), const SizedBox(height: 5), diff --git a/src/lib/features/user/view/user_profile_view.dart b/src/lib/features/user/view/user_profile_view.dart index 5dcdb32..2e71926 100644 --- a/src/lib/features/user/view/user_profile_view.dart +++ b/src/lib/features/user/view/user_profile_view.dart @@ -1,7 +1,5 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -import '../../../core/theme/app_colors.dart'; - import '../viewmodel/user_profile_viewmodel.dart'; import 'widgets/profile_header.dart'; import 'widgets/stat_card.dart'; @@ -15,23 +13,26 @@ class UserProfileView extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: AppColors.background, + backgroundColor: Theme.of(context).scaffoldBackgroundColor, appBar: AppBar( - backgroundColor: AppColors.background, + backgroundColor: Theme.of(context).scaffoldBackgroundColor, elevation: 0, centerTitle: true, scrolledUnderElevation: 0, - title: const Text( + title: Text( 'Profile', style: TextStyle( - color: AppColors.primaryBlue, + color: Theme.of(context).colorScheme.primary, fontWeight: FontWeight.w800, fontSize: 20, ), ), actions: [ IconButton( - icon: const Icon(Icons.settings, color: AppColors.primaryBlue), + icon: Icon( + Icons.settings, + color: Theme.of(context).colorScheme.primary, + ), onPressed: () {}, splashRadius: 24, ), @@ -42,16 +43,23 @@ class UserProfileView extends StatelessWidget { return AnimatedSwitcher( duration: const Duration(milliseconds: 300), child: vm.isLoading - ? const Center( + ? Center( key: ValueKey('loading'), - child: CircularProgressIndicator(color: AppColors.primaryBlue), + child: CircularProgressIndicator( + color: Theme.of(context).colorScheme.primary, + ), ) : vm.user == null ? const Center( key: ValueKey('error'), child: Text("Error loading profile"), ) - : _buildProfileContent(context, vm), + : Builder( + builder: (innerContext) { + vm.syncThemeWithProfile(innerContext); + return _buildProfileContent(innerContext, vm); + }, + ), ); }, ), @@ -98,33 +106,42 @@ class UserProfileView extends StatelessWidget { SettingsListTile( icon: Icons.notifications, title: 'Notifications', - iconBgColor: AppColors.border, - iconColor: AppColors.grayText, + iconBgColor: Theme.of(context).colorScheme.outline, + iconColor: Theme.of(context).colorScheme.onSurfaceVariant, onTap: () => vm.toggleNotification(!user.isNotificationEnabled), trailing: Switch( value: user.isNotificationEnabled, - activeColor: AppColors.white, - activeTrackColor: AppColors.primaryBlue, - inactiveThumbColor: AppColors.grayText, - inactiveTrackColor: AppColors.border, + activeColor: Theme.of(context).colorScheme.surface, + activeTrackColor: Theme.of(context).colorScheme.primary, + inactiveThumbColor: + Theme.of(context).colorScheme.onSurfaceVariant, + inactiveTrackColor: Theme.of(context).colorScheme.outline, onChanged: (val) => vm.toggleNotification(val), ), ), - const Divider(height: 1, indent: 64, endIndent: 24, color: AppColors.border), + Divider( + height: 1, + indent: 64, + endIndent: 24, + color: Theme.of(context).colorScheme.outline, + ), SettingsListTile( icon: Icons.dark_mode, title: 'Appearance', - iconBgColor: AppColors.border, - iconColor: AppColors.grayText, + iconBgColor: Theme.of(context).colorScheme.outline, + iconColor: Theme.of(context).colorScheme.onSurfaceVariant, trailing: Text( user.appearance, - style: const TextStyle( + style: TextStyle( fontSize: 14, fontWeight: FontWeight.w600, - color: AppColors.grayText, + color: Theme.of(context).colorScheme.onSurfaceVariant, ), ), - onTap: () {}, + onTap: () => vm.updateAppearance( + context, + user.appearance == 'Dark' ? 'Light' : 'Dark', + ), ), ], ), diff --git a/src/lib/features/user/view/widgets/logout_button.dart b/src/lib/features/user/view/widgets/logout_button.dart index 6484722..dd8fae1 100644 --- a/src/lib/features/user/view/widgets/logout_button.dart +++ b/src/lib/features/user/view/widgets/logout_button.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; class LogoutButton extends StatelessWidget { final VoidCallback onPressed; @@ -8,32 +7,34 @@ class LogoutButton extends StatelessWidget { @override Widget build(BuildContext context) { + final errorColor = Theme.of(context).colorScheme.error; + return Material( - color: AppColors.error.withOpacity(0.05), + color: errorColor.withOpacity(0.05), borderRadius: BorderRadius.circular(24), child: InkWell( onTap: onPressed, borderRadius: BorderRadius.circular(24), - splashColor: AppColors.error.withOpacity(0.1), - highlightColor: AppColors.error.withOpacity(0.05), + splashColor: errorColor.withOpacity(0.1), + highlightColor: errorColor.withOpacity(0.05), child: Container( width: double.infinity, padding: const EdgeInsets.symmetric(vertical: 20), decoration: BoxDecoration( borderRadius: BorderRadius.circular(24), - border: Border.all(color: AppColors.error.withOpacity(0.2)), + border: Border.all(color: errorColor.withOpacity(0.2)), ), - child: const Row( + child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - Icon(Icons.logout, color: AppColors.error, size: 22), - SizedBox(width: 12), + Icon(Icons.logout, color: errorColor, size: 22), + const SizedBox(width: 12), Text( 'Logout', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, - color: AppColors.error, + color: errorColor, ), ), ], diff --git a/src/lib/features/user/view/widgets/profile_header.dart b/src/lib/features/user/view/widgets/profile_header.dart index 4607c39..2e61342 100644 --- a/src/lib/features/user/view/widgets/profile_header.dart +++ b/src/lib/features/user/view/widgets/profile_header.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; // Adjust path based on your project structure import '../../model/user_profile_model.dart'; class ProfileHeader extends StatelessWidget { @@ -9,6 +8,12 @@ class ProfileHeader extends StatelessWidget { @override Widget build(BuildContext context) { + final avatarUri = Uri.tryParse(user.avatarUrl.trim()); + final hasValidAvatar = + avatarUri != null && + (avatarUri.scheme == 'http' || avatarUri.scheme == 'https') && + avatarUri.host.isNotEmpty; + return Column( children: [ Stack( @@ -20,7 +25,8 @@ class ProfileHeader extends StatelessWidget { borderRadius: BorderRadius.circular(32), boxShadow: [ BoxShadow( - color: AppColors.primaryBlue.withOpacity(0.15), + color: + Theme.of(context).colorScheme.primary.withValues(alpha: 0.15), blurRadius: 20, offset: const Offset(0, 10), ), @@ -28,39 +34,50 @@ class ProfileHeader extends StatelessWidget { ), child: ClipRRect( borderRadius: BorderRadius.circular(32), - child: Image.network( - user.avatarUrl, - width: 120, - height: 120, - fit: BoxFit.cover, - // Smooth image loading transition - frameBuilder: (context, child, frame, wasSynchronouslyLoaded) { - if (wasSynchronouslyLoaded) return child; - return AnimatedOpacity( - opacity: frame == null ? 0 : 1, - duration: const Duration(milliseconds: 500), - curve: Curves.easeOut, - child: child, - ); - }, - ), + child: hasValidAvatar + ? Image.network( + user.avatarUrl, + width: 120, + height: 120, + fit: BoxFit.cover, + errorBuilder: (_, __, ___) => _buildFallbackAvatar(context), + // Smooth image loading transition + frameBuilder: + (context, child, frame, wasSynchronouslyLoaded) { + if (wasSynchronouslyLoaded) return child; + return AnimatedOpacity( + opacity: frame == null ? 0 : 1, + duration: const Duration(milliseconds: 500), + curve: Curves.easeOut, + child: child, + ); + }, + ) + : _buildFallbackAvatar(context), ), ), // Edit Button with Ripple Material( - color: AppColors.primaryBlue, + color: Theme.of(context).colorScheme.primary, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), - side: const BorderSide(color: AppColors.background, width: 4), + side: BorderSide( + color: Theme.of(context).scaffoldBackgroundColor, + width: 4, + ), ), child: InkWell( borderRadius: BorderRadius.circular(12), onTap: () { // TODO: Handle Edit Profile action }, - child: const Padding( + child: Padding( padding: EdgeInsets.all(8.0), - child: Icon(Icons.edit, color: AppColors.white, size: 20), + child: Icon( + Icons.edit, + color: Theme.of(context).colorScheme.surface, + size: 20, + ), ), ), ), @@ -71,14 +88,27 @@ class ProfileHeader extends StatelessWidget { // Name Only Text( user.name, - style: const TextStyle( + style: TextStyle( fontSize: 24, fontWeight: FontWeight.w800, - color: AppColors.textDark, + color: Theme.of(context).colorScheme.onSurface, ), ), // Badges row removed here ], ); } + + Widget _buildFallbackAvatar(BuildContext context) { + return Container( + width: 120, + height: 120, + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: Icon( + Icons.person, + size: 64, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ); + } } \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/settings_list_tile.dart b/src/lib/features/user/view/widgets/settings_list_tile.dart index 2472243..6d18666 100644 --- a/src/lib/features/user/view/widgets/settings_list_tile.dart +++ b/src/lib/features/user/view/widgets/settings_list_tile.dart @@ -1,12 +1,11 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; class SettingsListTile extends StatelessWidget { final IconData icon; final String title; final Widget trailing; - final Color iconBgColor; - final Color iconColor; + final Color? iconBgColor; + final Color? iconColor; final VoidCallback? onTap; const SettingsListTile({ @@ -14,13 +13,17 @@ class SettingsListTile extends StatelessWidget { required this.icon, required this.title, required this.trailing, - this.iconBgColor = AppColors.backgroundBlue, - this.iconColor = AppColors.primaryBlue, + this.iconBgColor, + this.iconColor, this.onTap, }); @override Widget build(BuildContext context) { + final resolvedIconBgColor = + iconBgColor ?? Theme.of(context).colorScheme.surfaceContainerHighest; + final resolvedIconColor = iconColor ?? Theme.of(context).colorScheme.primary; + return InkWell( onTap: onTap, child: Padding( @@ -30,19 +33,19 @@ class SettingsListTile extends StatelessWidget { Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( - color: iconBgColor, + color: resolvedIconBgColor, shape: BoxShape.circle, ), - child: Icon(icon, color: iconColor, size: 22), + child: Icon(icon, color: resolvedIconColor, size: 22), ), const SizedBox(width: 16), Expanded( child: Text( title, - style: const TextStyle( + style: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, - color: AppColors.textDark, + color: Theme.of(context).colorScheme.onSurface, ), ), ), diff --git a/src/lib/features/user/view/widgets/settings_section.dart b/src/lib/features/user/view/widgets/settings_section.dart index be81a66..44cdff7 100644 --- a/src/lib/features/user/view/widgets/settings_section.dart +++ b/src/lib/features/user/view/widgets/settings_section.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; class SettingsSection extends StatelessWidget { final String title; @@ -16,16 +15,16 @@ class SettingsSection extends StatelessWidget { padding: const EdgeInsets.only(left: 16, bottom: 12), child: Text( title.toUpperCase(), - style: const TextStyle( + style: TextStyle( fontSize: 13, fontWeight: FontWeight.bold, - color: AppColors.grayText, + color: Theme.of(context).colorScheme.onSurfaceVariant, letterSpacing: 1.2, ), ), ), Material( - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(24), child: ClipRRect( borderRadius: BorderRadius.circular(24), diff --git a/src/lib/features/user/view/widgets/stat_card.dart b/src/lib/features/user/view/widgets/stat_card.dart index 2bfb80c..e0fef26 100644 --- a/src/lib/features/user/view/widgets/stat_card.dart +++ b/src/lib/features/user/view/widgets/stat_card.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; class StatCard extends StatelessWidget { final String value; @@ -11,7 +10,7 @@ class StatCard extends StatelessWidget { @override Widget build(BuildContext context) { return Material( - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(24), elevation: 0, child: InkWell( @@ -21,25 +20,25 @@ class StatCard extends StatelessWidget { padding: const EdgeInsets.symmetric(vertical: 24), decoration: BoxDecoration( borderRadius: BorderRadius.circular(24), - border: Border.all(color: AppColors.border.withOpacity(0.5)), + border: Border.all(color: Theme.of(context).colorScheme.outline.withOpacity(0.5)), ), child: Column( children: [ Text( value, - style: const TextStyle( + style: TextStyle( fontSize: 28, fontWeight: FontWeight.w800, - color: AppColors.primaryBlue, + color: Theme.of(context).colorScheme.primary, ), ), const SizedBox(height: 4), Text( label.toUpperCase(), - style: const TextStyle( + style: TextStyle( fontSize: 11, fontWeight: FontWeight.bold, - color: AppColors.grayText, + color: Theme.of(context).colorScheme.onSurfaceVariant, letterSpacing: 1.2, ), ), diff --git a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart index 6c8e05f..80caf9c 100644 --- a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart +++ b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart @@ -1,13 +1,16 @@ import 'package:flutter/material.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; +import 'package:provider/provider.dart'; // Import thêm Provider + +import '../../../core/theme/theme_provider.dart'; import '../../auth/presentation/view/auth_gate.dart'; import '../model/user_profile_model.dart'; import '../service/user_service.dart'; class UserProfileViewModel extends ChangeNotifier { final UserService _userService = UserService(); - final _supabase = Supabase.instance.client; + String? _lastAppliedAppearance; UserProfileModel? _user; UserProfileModel? get user => _user; @@ -22,8 +25,18 @@ class UserProfileViewModel extends ChangeNotifier { try { _user = await _userService.fetchUserProfile(); + _lastAppliedAppearance = null; } catch (e) { debugPrint("Error loading profile: $e"); + _user = UserProfileModel( + name: 'Alex Thompson', + avatarUrl: '', + appearance: 'Light', + tasksDone: 24, + streaks: 12, + isNotificationEnabled: true, + id: '', + ); } finally { _isLoading = false; notifyListeners(); @@ -35,20 +48,31 @@ class UserProfileViewModel extends ChangeNotifier { if (_user != null) { _user!.isNotificationEnabled = value; notifyListeners(); - // Ghi chú: Có thể dùng SharedPreferences để lưu local setting này } } - /// Handle theme/appearance change - void updateAppearance(String newAppearance) { + + void updateAppearance(BuildContext context, String newAppearance) { if (_user != null) { _user!.appearance = newAppearance; + _lastAppliedAppearance = newAppearance; notifyListeners(); - // Ghi chú: Chỗ này thường sẽ gọi Provider quản lý Theme tổng của App + + if (context.mounted) { + context.read().updateTheme(newAppearance); + } } } + void syncThemeWithProfile(BuildContext context) { + if (_user == null) return; + if (_lastAppliedAppearance == _user!.appearance) return; + + _lastAppliedAppearance = _user!.appearance; + context.read().updateTheme(_user!.appearance); + } + /// Logout Future logout(BuildContext context) async { try { await _supabase.auth.signOut(); diff --git a/src/lib/main.dart b/src/lib/main.dart index c726b17..0265c65 100644 --- a/src/lib/main.dart +++ b/src/lib/main.dart @@ -1,12 +1,13 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; import 'package:task_management_app/features/main/view/screens/main_screen.dart'; -import 'core/theme/app_colors.dart'; -import 'features/auth/presentation/view/login_view.dart'; -import 'features/auth/presentation/view/auth_gate.dart'; +import 'core/theme/app_theme.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; +import 'core/theme/theme_provider.dart'; + Future main() async { WidgetsFlutterBinding.ensureInitialized(); @@ -28,7 +29,12 @@ Future main() async { SystemChrome.setSystemUIOverlayStyle( const SystemUiOverlayStyle(statusBarColor: Colors.transparent)); - runApp(const TaskApp()); + runApp( + MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => ThemeProvider()), + ], + child: const TaskApp())); } // 4. Create a global variable for ViewModel to call API quickly @@ -41,20 +47,12 @@ class TaskApp extends StatelessWidget { @override Widget build(BuildContext context) { + final themeProvider = Provider.of(context); return MaterialApp( title: 'Task Management App', - theme: ThemeData( - scaffoldBackgroundColor: AppColors.backgroundBlue, - primaryColor: AppColors.primaryBlue, - useMaterial3: true, - fontFamily: 'Montserrat', - textTheme: const TextTheme( - headlineMedium: TextStyle(fontSize: 32, fontWeight: FontWeight.bold, color: Colors.black), - titleMedium: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black), - bodyMedium: TextStyle(fontSize: 14, color: AppColors.grayText), - labelLarge: TextStyle(fontSize: 16, color: AppColors.primaryBlue), - ), - ), + themeMode: themeProvider.themeMode, + theme: AppTheme.lightTheme, // Bộ màu sáng ông vừa map xong + darkTheme: AppTheme.darkTheme, home: const MainScreen(), debugShowCheckedModeBanner: false, ); From 4b0e58408ca18c736dd7d4a3c1a3aebfeee70c56 Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Thu, 9 Apr 2026 17:48:14 +0700 Subject: [PATCH 03/11] fix: black color theme --- .../main/view/screens/main_screen.dart | 2 +- src/lib/features/note/view/focus_screen.dart | 129 ++++++++++++++--- src/lib/features/note/view/focus_widget.dart | 130 ++++++++++++++---- .../user/model/user_profile_model.dart | 25 +++- .../viewmodel/user_profile_viewmodel.dart | 33 +++-- 5 files changed, 258 insertions(+), 61 deletions(-) diff --git a/src/lib/features/main/view/screens/main_screen.dart b/src/lib/features/main/view/screens/main_screen.dart index 77e3308..1cc5479 100644 --- a/src/lib/features/main/view/screens/main_screen.dart +++ b/src/lib/features/main/view/screens/main_screen.dart @@ -33,7 +33,7 @@ class _MainScreenState extends State { child: const StatisticsScreen(), ), ChangeNotifierProvider( - create: (_) => UserProfileViewModel()..loadProfile(), + create: (_) => UserProfileViewModel(useMockData: true)..loadProfile(), child: const UserProfileView(), ), const SettingsScreen(), diff --git a/src/lib/features/note/view/focus_screen.dart b/src/lib/features/note/view/focus_screen.dart index b487ace..01fcc72 100644 --- a/src/lib/features/note/view/focus_screen.dart +++ b/src/lib/features/note/view/focus_screen.dart @@ -9,6 +9,7 @@ class FocusScreen extends StatelessWidget { // Shows the configuration dialog for timer and notification settings void _showSettingsDialog(BuildContext context) { final vm = context.read(); + final isDark = Theme.of(context).brightness == Brightness.dark; double currentPomodoro = (vm.pomodoroTime / 60).toDouble(); double currentBreak = (vm.shortBreakTime / 60).toDouble(); @@ -21,9 +22,16 @@ class FocusScreen extends StatelessWidget { return StatefulBuilder( builder: (context, setStateDialog) { return AlertDialog( - backgroundColor: Colors.white, + backgroundColor: + isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), - title: const Text('Cài đặt', style: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + title: Text( + 'Cài đặt', + style: TextStyle( + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), content: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, @@ -33,7 +41,14 @@ class FocusScreen extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Text('Pomodoro', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + Text( + 'Pomodoro', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), + ), Text( '${currentPomodoro.toInt()} phút', style: TextStyle( @@ -55,29 +70,69 @@ class FocusScreen extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Text('Nghỉ ngắn', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + Text( + 'Nghỉ ngắn', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), + ), Text('${currentBreak.toInt()} phút', style: const TextStyle(color: Colors.orange, fontWeight: FontWeight.bold)), ], ), - Slider(value: currentBreak, min: 1, max: 30, divisions: 29, activeColor: Colors.orange, onChanged: (val) => setStateDialog(() => currentBreak = val)), - const Divider(height: 30), + Slider( + value: currentBreak, + min: 1, + max: 30, + divisions: 29, + activeColor: Colors.orange, + onChanged: (val) => setStateDialog(() => currentBreak = val), + ), + Divider( + height: 30, + color: Theme.of(context).colorScheme.outline, + ), // --- Hardware Settings --- SwitchListTile( - title: const Text('Rung', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + title: Text( + 'Rung', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), + ), value: currentVibrate, - activeColor: Theme.of(context).colorScheme.primary, + activeThumbColor: Theme.of(context).colorScheme.primary, contentPadding: EdgeInsets.zero, onChanged: (val) => setStateDialog(() => currentVibrate = val), ), const SizedBox(height: 10), - const Text('Âm thanh', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + Text( + 'Âm thanh', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), + ), const SizedBox(height: 10), Container( padding: const EdgeInsets.symmetric(horizontal: 15), - decoration: BoxDecoration(color: const Color(0xFFF4F6F9), borderRadius: BorderRadius.circular(15)), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF12223D) + : Theme.of(context).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(15), + ), child: DropdownButtonHideUnderline( child: DropdownButton( + dropdownColor: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, + style: TextStyle(color: Theme.of(context).colorScheme.onSurface), isExpanded: true, value: currentRingtone, items: const [ @@ -95,7 +150,14 @@ class FocusScreen extends StatelessWidget { ), ), actions: [ - TextButton(onPressed: () => Navigator.pop(context), child: const Text('Hủy', style: TextStyle(color: Colors.grey))), + TextButton( + onPressed: () => Navigator.pop(context), + child: Text( + 'Hủy', + style: + TextStyle(color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + ), ElevatedButton( onPressed: () { // Update settings in ViewModel @@ -118,23 +180,46 @@ class FocusScreen extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( backgroundColor: Theme.of(context).scaffoldBackgroundColor, - body: SafeArea( - child: SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), - child: Column( + body: Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, + ), + child: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), + child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ // --- Header --- Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Row( + Row( children: [ - CircleAvatar(radius: 22, backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=a042581f4e29026704d')), - SizedBox(width: 15), - Text('Tập trung', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + const CircleAvatar( + radius: 22, + backgroundImage: + NetworkImage('https://i.pravatar.cc/150?u=a042581f4e29026704d'), + ), + const SizedBox(width: 15), + Text( + 'Tập trung', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), ], ), // Settings Icon @@ -142,8 +227,10 @@ class FocusScreen extends StatelessWidget { onTap: () => _showSettingsDialog(context), child: Container( padding: const EdgeInsets.all(10), - decoration: const BoxDecoration( - color: Colors.white, + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF172744) + : Theme.of(context).colorScheme.surface, shape: BoxShape.circle, ), child: Icon( diff --git a/src/lib/features/note/view/focus_widget.dart b/src/lib/features/note/view/focus_widget.dart index e676057..73fb73b 100644 --- a/src/lib/features/note/view/focus_widget.dart +++ b/src/lib/features/note/view/focus_widget.dart @@ -10,13 +10,16 @@ class FocusTabSelector extends StatelessWidget { @override Widget build(BuildContext context) { final vm = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; return Container( padding: const EdgeInsets.all(5), decoration: BoxDecoration( - color: Colors.white, + color: isDark ? const Color(0xFF132544) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(20), - boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.02), blurRadius: 10)], + boxShadow: [ + BoxShadow(color: Colors.black.withValues(alpha: 0.10), blurRadius: 10) + ], ), child: Row( mainAxisSize: MainAxisSize.min, @@ -51,7 +54,9 @@ class FocusTabSelector extends StatelessWidget { padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 10), decoration: BoxDecoration( color: isSelected - ? Theme.of(context).colorScheme.primary + ? (Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF2A3D5D) + : Theme.of(context).colorScheme.primary) : Colors.transparent, borderRadius: BorderRadius.circular(15), ), @@ -77,13 +82,23 @@ class TimerDisplayWidget extends StatelessWidget { @override Widget build(BuildContext context) { final vm = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; + return Stack( alignment: Alignment.center, children: [ Container( width: 280, height: 280, - decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: Colors.white, width: 14)), + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: isDark + ? const Color(0xFF182C4D) + : Theme.of(context).colorScheme.surface, + width: 14, + ), + ), ), SizedBox( width: 280, @@ -100,16 +115,27 @@ class TimerDisplayWidget extends StatelessWidget { width: 210, height: 210, decoration: BoxDecoration( - color: Colors.white, + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, shape: BoxShape.circle, - boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 20, offset: const Offset(0, 10))], + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.18), + blurRadius: 20, + offset: const Offset(0, 10), + ) + ], ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( vm.timeString, - style: const TextStyle(fontSize: 56, fontWeight: FontWeight.w900, color: Color(0xFF2C3E50), letterSpacing: -2), + style: TextStyle( + fontSize: 56, + fontWeight: FontWeight.w900, + color: Theme.of(context).colorScheme.onSurface, + letterSpacing: -2, + ), ), const SizedBox(height: 4), Text( @@ -117,7 +143,10 @@ class TimerDisplayWidget extends StatelessWidget { style: TextStyle( fontSize: 12, fontWeight: FontWeight.bold, - color: Theme.of(context).colorScheme.primary.withOpacity(0.8), + color: Theme.of(context) + .colorScheme + .primary + .withValues(alpha: 0.85), letterSpacing: 2, ), ), @@ -136,13 +165,15 @@ class TimerControlsWidget extends StatelessWidget { @override Widget build(BuildContext context) { final vm = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; + return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ _buildControlBtn( icon: Icons.replay_rounded, - bgColor: Colors.white, - iconColor: const Color(0xFF757575), + bgColor: isDark ? const Color(0xFF1A2B4B) : Theme.of(context).colorScheme.surface, + iconColor: Theme.of(context).colorScheme.onSurfaceVariant, size: 60, onTap: vm.resetTimer, ), @@ -165,8 +196,8 @@ class TimerControlsWidget extends StatelessWidget { const SizedBox(width: 30), _buildControlBtn( icon: Icons.skip_next_rounded, - bgColor: Colors.white, - iconColor: const Color(0xFF757575), + bgColor: isDark ? const Color(0xFF1A2B4B) : Theme.of(context).colorScheme.surface, + iconColor: Theme.of(context).colorScheme.onSurfaceVariant, size: 60, onTap: vm.skipTimer, ), @@ -189,8 +220,18 @@ class TimerControlsWidget extends StatelessWidget { color: bgColor, shape: BoxShape.circle, boxShadow: [ - if (hasShadow) BoxShadow(color: bgColor.withOpacity(0.4), blurRadius: 20, offset: const Offset(0, 10)), - if (!hasShadow) BoxShadow(color: Colors.black.withOpacity(0.03), blurRadius: 10, offset: const Offset(0, 5)), + if (hasShadow) + BoxShadow( + color: bgColor.withValues(alpha: 0.40), + blurRadius: 20, + offset: const Offset(0, 10), + ), + if (!hasShadow) + BoxShadow( + color: Colors.black.withValues(alpha: 0.16), + blurRadius: 10, + offset: const Offset(0, 5), + ), ], ), child: Material( @@ -212,18 +253,32 @@ class QuickNoteCard extends StatelessWidget { @override Widget build(BuildContext context) { final vm = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; return Container( width: double.infinity, padding: const EdgeInsets.all(25), - decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(30)), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: const Color(0xFF2A3E62), width: 1) + : null, + ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Text('Ghi chú nhanh', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + Text( + 'Ghi chú nhanh', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), Text( 'Đang thực hiện', style: TextStyle( @@ -240,7 +295,9 @@ class QuickNoteCard extends StatelessWidget { Container( padding: const EdgeInsets.all(15), decoration: BoxDecoration( - color: const Color(0xFFF4F6F9), + color: isDark + ? const Color(0xFF12223D) + : Theme.of(context).colorScheme.surfaceContainerHighest, borderRadius: BorderRadius.circular(15), ), child: Column( @@ -251,12 +308,21 @@ class QuickNoteCard extends StatelessWidget { maxLines: 3, decoration: InputDecoration( hintText: 'Thêm ý tưởng, tiến độ, hình ảnh...', - hintStyle: TextStyle(color: Colors.grey.shade400, fontSize: 14), + hintStyle: TextStyle( + color: Theme.of(context) + .colorScheme + .onSurfaceVariant + .withValues(alpha: 0.70), + fontSize: 14, + ), border: InputBorder.none, isDense: true, contentPadding: EdgeInsets.zero, ), - style: const TextStyle(fontSize: 14, color: Color(0xFF2C3E50)), + style: TextStyle( + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), ), // SHOW IMAGE PREVIEW IF SELECTED @@ -309,7 +375,11 @@ class QuickNoteCard extends StatelessWidget { children: [ Row( children: [ - Icon(Icons.attach_file_rounded, color: Colors.grey.shade400, size: 22), + Icon( + Icons.attach_file_rounded, + color: Theme.of(context).colorScheme.onSurfaceVariant, + size: 22, + ), const SizedBox(width: 10), // IMAGE PICKER BUTTON GestureDetector( @@ -340,7 +410,10 @@ class QuickNoteCard extends StatelessWidget { // --- LOCAL NOTE LIST WITH IMAGE SUPPORT --- if (vm.notes.isNotEmpty) ...[ - const Padding(padding: EdgeInsets.symmetric(vertical: 15), child: Divider(color: Color(0xFFE2E8F0), height: 1)), + Padding( + padding: const EdgeInsets.symmetric(vertical: 15), + child: Divider(color: Theme.of(context).colorScheme.outline, height: 1), + ), ListView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), @@ -351,7 +424,11 @@ class QuickNoteCard extends StatelessWidget { margin: const EdgeInsets.only(bottom: 12), padding: const EdgeInsets.all(12), decoration: BoxDecoration( - color: note.pinned ? const Color(0xFFFFF8E1) : const Color(0xFFF8FAFC), + color: note.pinned + ? (isDark ? const Color(0xFF4A3B17) : const Color(0xFFFFF8E1)) + : (isDark + ? const Color(0xFF12223D) + : Theme.of(context).colorScheme.surfaceContainerHighest), borderRadius: BorderRadius.circular(15), border: Border.all(color: note.pinned ? Colors.amber.shade200 : Colors.transparent), ), @@ -380,7 +457,14 @@ class QuickNoteCard extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ if (note.content.isNotEmpty) - Text(note.content, style: const TextStyle(fontSize: 14, color: Color(0xFF2C3E50), height: 1.4)), + Text( + note.content, + style: TextStyle( + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + height: 1.4, + ), + ), // DISPLAY ATTACHED IMAGE IN NOTE if (note.imagePath != null && note.imagePath!.isNotEmpty) ...[ diff --git a/src/lib/features/user/model/user_profile_model.dart b/src/lib/features/user/model/user_profile_model.dart index c808f55..47db9a6 100644 --- a/src/lib/features/user/model/user_profile_model.dart +++ b/src/lib/features/user/model/user_profile_model.dart @@ -18,15 +18,28 @@ class UserProfileModel { }); factory UserProfileModel.fromJson(Map json) { + int parseInt(dynamic value) { + if (value is int) return value; + if (value is num) return value.toInt(); + if (value is String) return int.tryParse(value) ?? 0; + return 0; + } + return UserProfileModel( // Dùng as String? để ép kiểu an toàn, kèm ?? để gán giá trị mặc định nếu bị null id: json['id'] as String? ?? '', - name: json['name'] as String? ?? 'Unknown User', - tasksDone: json['tasksDone'] as int? ?? 0, - streaks: json['streaks'] as int? ?? 0, - avatarUrl: json['avatarUrl'] as String? ?? '', - isNotificationEnabled: json['isNotificationEnabled'] as bool? ?? true, - appearance: json['appearance'] as String? ?? 'Light', + name: + (json['name'] ?? json['full_name'] ?? json['username']) as String? ?? + 'Unknown User', + tasksDone: parseInt(json['tasksDone'] ?? json['tasks_done']), + streaks: parseInt(json['streaks'] ?? json['streak_count']), + avatarUrl: + (json['avatarUrl'] ?? json['avatar_url'] ?? json['avatar']) as String? ?? + '', + isNotificationEnabled: + (json['isNotificationEnabled'] ?? json['is_notification_enabled']) as bool? ?? + true, + appearance: (json['appearance'] ?? json['theme_mode']) as String? ?? 'Light', ); } diff --git a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart index 80caf9c..21b28c0 100644 --- a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart +++ b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart @@ -10,8 +10,11 @@ import '../service/user_service.dart'; class UserProfileViewModel extends ChangeNotifier { final UserService _userService = UserService(); final _supabase = Supabase.instance.client; + final bool useMockData; String? _lastAppliedAppearance; + UserProfileViewModel({this.useMockData = true}); + UserProfileModel? _user; UserProfileModel? get user => _user; @@ -24,25 +27,35 @@ class UserProfileViewModel extends ChangeNotifier { notifyListeners(); try { - _user = await _userService.fetchUserProfile(); + if (useMockData) { + await Future.delayed(const Duration(milliseconds: 400)); + _user = _buildMockUser(); + } else { + _user = await _userService.fetchUserProfile(); + } _lastAppliedAppearance = null; } catch (e) { debugPrint("Error loading profile: $e"); - _user = UserProfileModel( - name: 'Alex Thompson', - avatarUrl: '', - appearance: 'Light', - tasksDone: 24, - streaks: 12, - isNotificationEnabled: true, - id: '', - ); + _user = _buildMockUser(); } finally { _isLoading = false; notifyListeners(); } } + UserProfileModel _buildMockUser() { + return UserProfileModel( + id: 'mock-user-001', + name: 'Alex Thompson', + // Valid URL so profile header can test normal network-avatar path. + avatarUrl: 'https://i.pravatar.cc/300?img=12', + appearance: 'Dark', + tasksDone: 24, + streaks: 12, + isNotificationEnabled: true, + ); + } + /// Toggle notification preference void toggleNotification(bool value) { if (_user != null) { From 2a401b1ced8fe1a57ff6a519c00fac1ba8225383 Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Thu, 9 Apr 2026 17:59:15 +0700 Subject: [PATCH 04/11] fix: black theme in statistics screen --- src/lib/features/note/view/focus_screen.dart | 1 + .../view/screens/statistics_screen.dart | 136 +++++++++++------- .../view/widgets/statistics_widgets.dart | 84 +++++++++-- 3 files changed, 153 insertions(+), 68 deletions(-) diff --git a/src/lib/features/note/view/focus_screen.dart b/src/lib/features/note/view/focus_screen.dart index 01fcc72..2702c2d 100644 --- a/src/lib/features/note/view/focus_screen.dart +++ b/src/lib/features/note/view/focus_screen.dart @@ -256,6 +256,7 @@ class FocusScreen extends StatelessWidget { ), ), ), + ) ); } } \ No newline at end of file diff --git a/src/lib/features/statistics/view/screens/statistics_screen.dart b/src/lib/features/statistics/view/screens/statistics_screen.dart index abdf952..fd18a14 100644 --- a/src/lib/features/statistics/view/screens/statistics_screen.dart +++ b/src/lib/features/statistics/view/screens/statistics_screen.dart @@ -28,25 +28,24 @@ class _StatisticsScreenState extends State { } - Icon _getIconForCategory(BuildContext context, String category) { - switch (category) { - case 'Design': - return Icon( - Icons.checklist_rtl_rounded, - color: Theme.of(context).colorScheme.primary, - ); - case 'Research': return const Icon(Icons.timer_outlined, color: Color(0xFFE67E22)); - case 'Development': return const Icon(Icons.calendar_month_outlined, color: Color(0xFF9B59B6)); - default: return const Icon(Icons.task_alt_rounded, color: Colors.green); - } - } - @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( backgroundColor: Theme.of(context).scaffoldBackgroundColor, - body: Consumer( - builder: (context, viewModel, child) { + body: Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, + ), + child: Consumer( + builder: (context, viewModel, child) { if (viewModel.isLoading) { return const Center(child: CircularProgressIndicator()); @@ -66,37 +65,51 @@ class _StatisticsScreenState extends State { final currentTasks = data.recentTasks; - return SafeArea( - child: SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ + return SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ // --- Header --- - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Row( - children: [ - CircleAvatar( + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + const CircleAvatar( radius: 22, - backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=a042581f4e29026704d') - ), - SizedBox(width: 15), - Text('Thống kê', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), - ], - ), + backgroundImage: NetworkImage( + 'https://i.pravatar.cc/150?u=a042581f4e29026704d', + ), + ), + const SizedBox(width: 15), + Text( + 'Thống kê', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + ], + ), Container( padding: const EdgeInsets.all(10), - decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF172744) + : Theme.of(context).colorScheme.surface, + shape: BoxShape.circle, + ), child: Icon( Icons.notifications_none_rounded, color: Theme.of(context).colorScheme.primary, ), ) - ], - ), - const SizedBox(height: 30), + ], + ), + const SizedBox(height: 30), DailyProgressCard( @@ -120,10 +133,17 @@ class _StatisticsScreenState extends State { const SizedBox(height: 30), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Text('Hoàn thành gần đây', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Hoàn thành gần đây', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), Text( 'Xem tất cả', style: TextStyle( @@ -132,20 +152,25 @@ class _StatisticsScreenState extends State { color: Theme.of(context).colorScheme.primary, ), ), - ], - ), - const SizedBox(height: 15), + ], + ), + const SizedBox(height: 15), AnimatedSwitcher( duration: const Duration(milliseconds: 300), child: currentTasks.isEmpty ? Container( - key: const ValueKey('empty_state'), - padding: const EdgeInsets.all(30), - alignment: Alignment.center, - child: Text('Chưa có công việc nào hoàn thành gần đây.', - style: TextStyle(color: Colors.grey.shade500), textAlign: TextAlign.center), - ) + key: const ValueKey('empty_state'), + padding: const EdgeInsets.all(30), + alignment: Alignment.center, + child: Text( + 'Chưa có công việc nào hoàn thành gần đây.', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + textAlign: TextAlign.center, + ), + ) : Column( key: ValueKey('list_$_selectedDayIndex'), children: currentTasks.map((task) { @@ -161,12 +186,13 @@ class _StatisticsScreenState extends State { ), ), - const SizedBox(height: 80), - ], + const SizedBox(height: 80), + ], + ), ), - ), - ); - }, + ); + }, + ), ), ); } diff --git a/src/lib/features/statistics/view/widgets/statistics_widgets.dart b/src/lib/features/statistics/view/widgets/statistics_widgets.dart index 7ff72cd..c0b6568 100644 --- a/src/lib/features/statistics/view/widgets/statistics_widgets.dart +++ b/src/lib/features/statistics/view/widgets/statistics_widgets.dart @@ -11,12 +11,17 @@ class DailyProgressCard extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Container( width: double.infinity, padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 20), decoration: BoxDecoration( - color: Colors.white, + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: const Color(0xFF2A3E62), width: 1) + : null, ), child: Column( children: [ @@ -47,8 +52,21 @@ class DailyProgressCard extends StatelessWidget { Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text('$completed/$total', style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), - Text('Công việc', style: TextStyle(fontSize: 12, color: Colors.grey.shade500)), + Text( + '$completed/$total', + style: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + Text( + 'Công việc', + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), ], @@ -58,7 +76,10 @@ class DailyProgressCard extends StatelessWidget { RichText( textAlign: TextAlign.center, text: TextSpan( - style: const TextStyle(fontSize: 16, color: Colors.black87), + style: TextStyle( + fontSize: 16, + color: Theme.of(context).colorScheme.onSurface, + ), children: [ const TextSpan(text: 'Tuyệt vời! Bạn đã hoàn thành '), TextSpan( @@ -97,18 +118,24 @@ class WeeklyChartCard extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; final bool isPositive = growthPercentage >= 0; - final Color trendColor = isPositive ? const Color(0xFF2ECC71) : Colors.redAccent; - final Color trendBgColor = isPositive ? const Color(0xFFE9F7EF) : const Color(0xFFFFEBEE); + final Color trendColor = isPositive ? const Color(0xFF3DDC84) : Colors.redAccent; + final Color trendBgColor = isPositive + ? (isDark ? const Color(0xFF173B3D) : const Color(0xFFE9F7EF)) + : (isDark ? const Color(0xFF402129) : const Color(0xFFFFEBEE)); final String trendText = "${isPositive ? '+' : ''}$growthPercentage% vs tuần trước"; return Container( width: double.infinity, padding: const EdgeInsets.all(25), decoration: BoxDecoration( - color: Colors.white, + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: const Color(0xFF2A3E62), width: 1) + : null, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -129,7 +156,14 @@ class WeeklyChartCard extends StatelessWidget { ), ), const SizedBox(height: 5), - Text('$thisWeekTotal Tasks', style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + Text( + '$thisWeekTotal Tasks', + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), ], ), Container( @@ -173,7 +207,9 @@ class WeeklyChartCard extends StatelessWidget { decoration: BoxDecoration( color: isActive ? Theme.of(context).colorScheme.primary - : const Color(0xFFF5F7FA), + : (Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF334764) + : const Color(0xFFF5F7FA)), borderRadius: BorderRadius.circular(8), ), ), @@ -203,6 +239,7 @@ class CompletedTaskCard extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; final time = task.updatedAt; final hour = time.hour > 12 ? time.hour - 12 : (time.hour == 0 ? 12 : time.hour); @@ -239,14 +276,22 @@ class CompletedTaskCard extends StatelessWidget { margin: const EdgeInsets.only(bottom: 15), padding: const EdgeInsets.all(20), decoration: BoxDecoration( - color: Colors.white, + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(25), + border: isDark + ? Border.all(color: const Color(0xFF2A3E62), width: 1) + : null, ), child: Row( children: [ Container( padding: const EdgeInsets.all(12), - decoration: BoxDecoration(color: const Color(0xFFF1F7FD), borderRadius: BorderRadius.circular(15)), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF23395D) + : const Color(0xFFF1F7FD), + borderRadius: BorderRadius.circular(15), + ), child: icon, ), const SizedBox(width: 15), @@ -254,9 +299,22 @@ class CompletedTaskCard extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(task.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + Text( + task.title, + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), const SizedBox(height: 4), - Text(timeString, style: TextStyle(fontSize: 12, color: Colors.grey.shade500)), + Text( + timeString, + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), ), From 48688a88f5793c4c91a1c040be0a23bf40066a62 Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Thu, 9 Apr 2026 18:27:10 +0700 Subject: [PATCH 05/11] feat: add dark theme to auth screen --- src/lib/core/theme/auth_layout_template.dart | 109 +++++++++++++----- src/lib/core/theme/custom_text_field.dart | 30 +++-- .../view/forgot_password_view.dart | 57 +++++---- .../presentation/view/new_password_view.dart | 11 +- .../view/otp_verification_view.dart | 56 ++++++--- .../user/model/user_profile_model.dart | 1 - src/lib/main.dart | 4 +- 7 files changed, 193 insertions(+), 75 deletions(-) diff --git a/src/lib/core/theme/auth_layout_template.dart b/src/lib/core/theme/auth_layout_template.dart index d16feb4..e001784 100644 --- a/src/lib/core/theme/auth_layout_template.dart +++ b/src/lib/core/theme/auth_layout_template.dart @@ -34,6 +34,8 @@ class AuthLayoutTemplate extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( backgroundColor: Theme.of(context).scaffoldBackgroundColor, appBar: AppBar( @@ -41,29 +43,50 @@ class AuthLayoutTemplate extends StatelessWidget { elevation: 0, leading: Navigator.canPop(context) ? IconButton( - icon: Icon( - Icons.arrow_back, - color: Theme.of(context).colorScheme.primary, + icon: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: isDark + ? const Color(0xFF172744) + : Theme.of(context).colorScheme.surface, + ), + child: Icon( + Icons.arrow_back, + color: Theme.of(context).colorScheme.primary, + ), ), onPressed: () => Navigator.pop(context), ) : null, ), - body: SafeArea( - child: Center( - child: SingleChildScrollView( - padding: const EdgeInsets.fromLTRB(24.0, 16.0, 24.0, 48.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - _buildHeader(context), - const SizedBox(height: 32), - useCard - ? _buildCardContainer(context) - : _buildTransparentContainer(context), - const SizedBox(height: 32), - if (footerContent != null) footerContent!, - ], + body: Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, + ), + child: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(24.0, 16.0, 24.0, 48.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _buildHeader(context), + const SizedBox(height: 32), + useCard + ? _buildCardContainer(context) + : _buildTransparentContainer(context), + const SizedBox(height: 32), + if (footerContent != null) footerContent!, + ], + ), ), ), ), @@ -72,6 +95,8 @@ class AuthLayoutTemplate extends StatelessWidget { } Widget _buildHeader(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Column( children: [ customHeaderIcon ?? @@ -79,11 +104,11 @@ class AuthLayoutTemplate extends StatelessWidget { width: 80, height: 80, decoration: BoxDecoration( - color: Theme.of(context).colorScheme.surface, + color: isDark ? const Color(0xFF1E2B47) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(24), boxShadow: [ BoxShadow( - color: Theme.of(context).colorScheme.primary.withOpacity(0.1), + color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.14), blurRadius: 20, offset: const Offset(0, 10), ), @@ -122,14 +147,17 @@ class AuthLayoutTemplate extends StatelessWidget { } Widget _buildCardContainer(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Container( padding: const EdgeInsets.all(32), decoration: BoxDecoration( - color: Theme.of(context).colorScheme.surface, + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(32), + border: isDark ? Border.all(color: const Color(0xFF2A3E62), width: 1) : null, boxShadow: [ BoxShadow( - color: Theme.of(context).colorScheme.primary.withOpacity(0.08), + color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.12), blurRadius: 30, offset: const Offset(0, 10), ), @@ -143,6 +171,8 @@ class AuthLayoutTemplate extends StatelessWidget { _buildFormElements(context); Widget _buildFormElements(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -154,12 +184,15 @@ class AuthLayoutTemplate extends StatelessWidget { style: ElevatedButton.styleFrom( backgroundColor: Theme.of(context).colorScheme.primary, disabledBackgroundColor: - Theme.of(context).colorScheme.primary.withOpacity(0.6), + Theme.of(context).colorScheme.primary.withValues(alpha: 0.6), padding: const EdgeInsets.symmetric(vertical: 20), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), - elevation: isLoading ? 0 : 4, + elevation: isLoading ? 0 : (isDark ? 8 : 4), + shadowColor: isDark + ? Theme.of(context).colorScheme.primary.withValues(alpha: 0.35) + : null, ), child: isLoading ? SizedBox( @@ -197,11 +230,15 @@ class AuthLayoutTemplate extends StatelessWidget { Expanded( child: Divider(color: Theme.of(context).colorScheme.outline), ), - const Padding( + Padding( padding: EdgeInsets.symmetric(horizontal: 16), child: Text( 'OR', - style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold), + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), ), ), Expanded( @@ -214,6 +251,16 @@ class AuthLayoutTemplate extends StatelessWidget { children: [ Expanded( child: OutlinedButton.icon( + style: OutlinedButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.onSurface, + side: BorderSide(color: Theme.of(context).colorScheme.outline), + backgroundColor: + isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + padding: const EdgeInsets.symmetric(vertical: 14), + ), onPressed: onGoogleTap, icon: const Icon( Icons.g_mobiledata, @@ -226,6 +273,16 @@ class AuthLayoutTemplate extends StatelessWidget { const SizedBox(width: 16), Expanded( child: OutlinedButton.icon( + style: OutlinedButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.onSurface, + side: BorderSide(color: Theme.of(context).colorScheme.outline), + backgroundColor: + isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + padding: const EdgeInsets.symmetric(vertical: 14), + ), onPressed: onFacebookTap, icon: const Icon(Icons.facebook, color: Color(0xFF1877F2)), label: const Text('Facebook'), diff --git a/src/lib/core/theme/custom_text_field.dart b/src/lib/core/theme/custom_text_field.dart index 1f73215..05a651d 100644 --- a/src/lib/core/theme/custom_text_field.dart +++ b/src/lib/core/theme/custom_text_field.dart @@ -23,6 +23,8 @@ class CustomTextField extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Padding( padding: const EdgeInsets.only(bottom: 16), child: Column( @@ -35,7 +37,10 @@ class CustomTextField extends StatelessWidget { style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, - color: Theme.of(context).colorScheme.onSurface.withOpacity(0.6), + color: Theme.of(context) + .colorScheme + .onSurfaceVariant + .withValues(alpha: isDark ? 0.9 : 0.8), letterSpacing: 1, ), ), @@ -51,18 +56,21 @@ class CustomTextField extends StatelessWidget { decoration: InputDecoration( hintText: hint, hintStyle: TextStyle( - color: Theme.of(context).colorScheme.onSurface.withOpacity(0.3), + color: Theme.of(context) + .colorScheme + .onSurfaceVariant + .withValues(alpha: 0.65), fontWeight: FontWeight.w400, fontSize: 16, ), filled: true, - fillColor: Theme.of(context).colorScheme.surface, + fillColor: isDark ? const Color(0xFF344765) : Theme.of(context).colorScheme.surface, prefixIcon: Icon(icon, color: Theme.of(context).colorScheme.primary), suffixIcon: isPassword ? IconButton( icon: Icon( obscureText ? Icons.visibility_off : Icons.visibility, - color: Colors.grey, + color: Theme.of(context).colorScheme.onSurfaceVariant, ), onPressed: onToggleVisibility, ) @@ -72,18 +80,22 @@ class CustomTextField extends StatelessWidget { horizontal: 16, ), border: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), + borderRadius: BorderRadius.circular(24), borderSide: BorderSide.none, ), enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), - borderSide: BorderSide(color: Theme.of(context).colorScheme.outline), + borderRadius: BorderRadius.circular(24), + borderSide: BorderSide( + color: isDark + ? const Color(0xFF4A5F80) + : Theme.of(context).colorScheme.outline, + ), ), focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), + borderRadius: BorderRadius.circular(24), borderSide: BorderSide( color: Theme.of(context).colorScheme.primary, - width: 2, + width: 1.5, ), ), ), diff --git a/src/lib/features/auth/presentation/view/forgot_password_view.dart b/src/lib/features/auth/presentation/view/forgot_password_view.dart index 833b0a8..8029cca 100644 --- a/src/lib/features/auth/presentation/view/forgot_password_view.dart +++ b/src/lib/features/auth/presentation/view/forgot_password_view.dart @@ -15,6 +15,8 @@ class _ForgotPasswordViewState extends State { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return AnimatedBuilder( animation: _vm, builder: (context, _) => AuthLayoutTemplate( @@ -26,9 +28,16 @@ class _ForgotPasswordViewState extends State { customHeaderIcon: Container( width: 120, height: 120, decoration: BoxDecoration( - color: Theme.of(context).colorScheme.surface, + color: isDark ? const Color(0xFF1B2A46) : Theme.of(context).colorScheme.surface, shape: BoxShape.circle, - boxShadow: const [BoxShadow(color: Color(0xFFD1D9E6), blurRadius: 16)], + boxShadow: [ + BoxShadow( + color: isDark + ? Theme.of(context).colorScheme.primary.withValues(alpha: 0.22) + : const Color(0xFFD1D9E6), + blurRadius: 24, + ) + ], ), child: Icon( Icons.lock_reset, @@ -63,25 +72,33 @@ class _ForgotPasswordViewState extends State { controller: _vm.emailCtrl, ), footerContent: Padding( - padding: EdgeInsets.only(bottom: 24.0), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon( - Icons.help, - size: 16, - color: Theme.of(context).colorScheme.primary, - ), - const SizedBox(width: 4), - Text( - 'Cần hỗ trợ? Liên hệ CSKH', - style: TextStyle( - color: Theme.of(context).colorScheme.onSurfaceVariant, - fontSize: 14, - fontWeight: FontWeight.bold, + padding: const EdgeInsets.only(bottom: 24.0), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF111E37) : Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(999), + border: Border.all(color: Theme.of(context).colorScheme.outline), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.help, + size: 16, + color: Theme.of(context).colorScheme.primary, ), - ), - ], + const SizedBox(width: 8), + Text( + 'Cần hỗ trợ? Liên hệ CSKH', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 14, + fontWeight: FontWeight.bold, + ), + ), + ], + ), ), ), ), diff --git a/src/lib/features/auth/presentation/view/new_password_view.dart b/src/lib/features/auth/presentation/view/new_password_view.dart index 31e50d1..64c6e84 100644 --- a/src/lib/features/auth/presentation/view/new_password_view.dart +++ b/src/lib/features/auth/presentation/view/new_password_view.dart @@ -15,6 +15,8 @@ class _NewPasswordViewState extends State { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return AnimatedBuilder( animation: _vm, builder: (context, _) => AuthLayoutTemplate( @@ -24,7 +26,7 @@ class _NewPasswordViewState extends State { isLoading: _vm.isLoading, customHeaderIcon: CircleAvatar( radius: 40, - backgroundColor: Color(0xFFEBF2FF), + backgroundColor: isDark ? const Color(0xFF213A63) : const Color(0xFFEBF2FF), child: Icon( Icons.lock_reset, size: 40, @@ -72,8 +74,13 @@ class _NewPasswordViewState extends State { Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( - color: const Color(0xFFEBF2FF), + color: isDark + ? const Color(0xFF223A63) + : const Color(0xFFEBF2FF), borderRadius: BorderRadius.circular(12), + border: isDark + ? Border.all(color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.25)) + : null, ), child: Row( children: [ diff --git a/src/lib/features/auth/presentation/view/otp_verification_view.dart b/src/lib/features/auth/presentation/view/otp_verification_view.dart index bdf3e77..6bd64c8 100644 --- a/src/lib/features/auth/presentation/view/otp_verification_view.dart +++ b/src/lib/features/auth/presentation/view/otp_verification_view.dart @@ -14,6 +14,8 @@ class _OtpVerificationViewState extends State { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( backgroundColor: Theme.of(context).scaffoldBackgroundColor, appBar: AppBar( @@ -29,22 +31,32 @@ class _OtpVerificationViewState extends State { title: Text( 'Xác thực OTP', style: TextStyle( - color: Theme.of(context).colorScheme.primary, + color: Theme.of(context).colorScheme.onSurface, fontWeight: FontWeight.bold, fontSize: 18, ), ), centerTitle: true, ), - body: AnimatedBuilder( - animation: _vm, - builder: (context, child) { - return SafeArea( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ + body: Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, + ), + child: AnimatedBuilder( + animation: _vm, + builder: (context, child) { + return SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ Icon( Icons.mark_email_read, size: 80, @@ -100,6 +112,11 @@ class _OtpVerificationViewState extends State { backgroundColor: Theme.of(context).colorScheme.primary, minimumSize: const Size(double.infinity, 56), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + elevation: isDark ? 10 : null, + shadowColor: Theme.of(context) + .colorScheme + .primary + .withValues(alpha: 0.35), ), child: _vm.isLoading ? CircularProgressIndicator( @@ -150,11 +167,12 @@ class _OtpVerificationViewState extends State { ), ), ) - ], + ], + ), ), - ), - ); - } + ); + } + ), ), ); } @@ -163,9 +181,15 @@ class _OtpVerificationViewState extends State { return Container( width: 35, height: 48, // Thu nhỏ kích thước ô lại để nhét vừa 8 ô trên 1 dòng decoration: BoxDecoration( - color: Theme.of(context).colorScheme.surface, + color: Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF344765) + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(8), - border: Border.all(color: Theme.of(context).colorScheme.outline), + border: Border.all( + color: Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF4A5F80) + : Theme.of(context).colorScheme.outline, + ), ), child: TextField( onChanged: (value) { diff --git a/src/lib/features/user/model/user_profile_model.dart b/src/lib/features/user/model/user_profile_model.dart index 47db9a6..d378b4b 100644 --- a/src/lib/features/user/model/user_profile_model.dart +++ b/src/lib/features/user/model/user_profile_model.dart @@ -26,7 +26,6 @@ class UserProfileModel { } return UserProfileModel( - // Dùng as String? để ép kiểu an toàn, kèm ?? để gán giá trị mặc định nếu bị null id: json['id'] as String? ?? '', name: (json['name'] ?? json['full_name'] ?? json['username']) as String? ?? diff --git a/src/lib/main.dart b/src/lib/main.dart index 0265c65..f9ab4e5 100644 --- a/src/lib/main.dart +++ b/src/lib/main.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; +import 'package:task_management_app/features/auth/presentation/view/auth_gate.dart'; +import 'package:task_management_app/features/auth/presentation/view/login_view.dart'; import 'package:task_management_app/features/main/view/screens/main_screen.dart'; import 'core/theme/app_theme.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -53,7 +55,7 @@ class TaskApp extends StatelessWidget { themeMode: themeProvider.themeMode, theme: AppTheme.lightTheme, // Bộ màu sáng ông vừa map xong darkTheme: AppTheme.darkTheme, - home: const MainScreen(), + home: const LoginView(), debugShowCheckedModeBanner: false, ); } From 7db7ab3ee8c2085a0c31e9b371bab0e2b7d087ce Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Thu, 9 Apr 2026 18:45:03 +0700 Subject: [PATCH 06/11] feat: apply dark theme for bottom navigation bar --- .../main/view/screens/main_screen.dart | 12 ++++- .../view/screens/create_task_screen.dart | 45 +++++++++++++++---- .../tasks/view/screens/home_screen.dart | 42 ++++++++++++++--- .../view/screens/task_detail_screen.dart | 44 +++++++++++++++--- .../tasks/view/widgets/task_widgets.dart | 21 ++++++--- src/lib/main.dart | 2 +- 6 files changed, 137 insertions(+), 29 deletions(-) diff --git a/src/lib/features/main/view/screens/main_screen.dart b/src/lib/features/main/view/screens/main_screen.dart index 1cc5479..cb1c9d0 100644 --- a/src/lib/features/main/view/screens/main_screen.dart +++ b/src/lib/features/main/view/screens/main_screen.dart @@ -41,6 +41,8 @@ class _MainScreenState extends State { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( extendBody: true, body: IndexedStack( @@ -50,7 +52,9 @@ class _MainScreenState extends State { bottomNavigationBar: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 15), decoration: BoxDecoration( - color: Colors.white, + color: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, borderRadius: const BorderRadius.only(topLeft: Radius.circular(30), topRight: Radius.circular(30)), boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 20, offset: const Offset(0, -5))], ), @@ -80,7 +84,11 @@ class _MainScreenState extends State { curve: Curves.easeInOut, padding: EdgeInsets.symmetric(horizontal: isSelected ? 15 : 10, vertical: 10), decoration: BoxDecoration( - color: isSelected ? const Color(0xFFE8F0FE) : Colors.transparent, + color: isSelected + ? (Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF23395D) + : const Color(0xFFE8F0FE)) + : Colors.transparent, borderRadius: BorderRadius.circular(15), ), child: Column( diff --git a/src/lib/features/tasks/view/screens/create_task_screen.dart b/src/lib/features/tasks/view/screens/create_task_screen.dart index 897153b..43ad594 100644 --- a/src/lib/features/tasks/view/screens/create_task_screen.dart +++ b/src/lib/features/tasks/view/screens/create_task_screen.dart @@ -21,14 +21,16 @@ class _CreateTaskScreenState extends State { @override Widget build(BuildContext context) { String formattedDate = DateFormat('EEEE, d MMMM').format(_selectedDate); + final isDark = Theme.of(context).brightness == Brightness.dark; return Scaffold( + backgroundColor: Theme.of(context).scaffoldBackgroundColor, body: SafeArea( child: Column( children: [ Container( decoration: BoxDecoration( - color: Colors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: const BorderRadius.only( bottomLeft: Radius.circular(30), bottomRight: Radius.circular(30)), boxShadow: [ @@ -42,11 +44,20 @@ class _CreateTaskScreenState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( - icon: const Icon(Icons.arrow_back_ios_new_rounded, color: Colors.black), + icon: Icon( + Icons.arrow_back_ios_new_rounded, + color: Theme.of(context).colorScheme.onSurface, + ), onPressed: () => Navigator.pop(context), ), - const Icon(Icons.menu_rounded, color: Colors.black), - const Icon(Icons.assignment_outlined, color: Colors.black), + Icon( + Icons.menu_rounded, + color: Theme.of(context).colorScheme.onSurface, + ), + Icon( + Icons.assignment_outlined, + color: Theme.of(context).colorScheme.onSurface, + ), ], ), ), @@ -76,7 +87,9 @@ class _CreateTaskScreenState extends State { label: Text(categories[index]), selected: isSelected, onSelected: (selected) => setState(() => _selectedCategoryIndex = selected ? index : 0), - backgroundColor: const Color(0xFFF1F7FD), + backgroundColor: isDark + ? Theme.of(context).colorScheme.surfaceContainerHighest + : const Color(0xFFF1F7FD), selectedColor: Theme.of(context).colorScheme.primary, labelStyle: TextStyle( color: isSelected @@ -86,7 +99,12 @@ class _CreateTaskScreenState extends State { ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), - side: const BorderSide(color: Color(0xFFF1F7FD), width: 1)), + side: BorderSide( + color: isDark + ? Theme.of(context).colorScheme.outline + : const Color(0xFFF1F7FD), + width: 1, + )), showCheckmark: false, ), ); @@ -112,9 +130,20 @@ class _CreateTaskScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(formattedDate, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + Text( + formattedDate, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), const SizedBox(height: 5), - Container(width: 150, height: 1, color: Colors.black26) + Container( + width: 150, + height: 1, + color: Theme.of(context).colorScheme.outline, + ) ], ), ) diff --git a/src/lib/features/tasks/view/screens/home_screen.dart b/src/lib/features/tasks/view/screens/home_screen.dart index 62c6623..0232c40 100644 --- a/src/lib/features/tasks/view/screens/home_screen.dart +++ b/src/lib/features/tasks/view/screens/home_screen.dart @@ -10,6 +10,7 @@ class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { String formattedDate = DateFormat('EEEE, d MMMM').format(DateTime.now()); + final isDark = Theme.of(context).brightness == Brightness.dark; // --- TẠO DỮ LIỆU GIẢ LẬP (MOCK DATA) --- final task1 = TaskModel( @@ -52,10 +53,20 @@ class HomeScreen extends StatelessWidget { child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Icon(Icons.menu_rounded, color: Colors.black), + Icon( + Icons.menu_rounded, + color: isDark + ? Theme.of(context).colorScheme.surface + : Colors.black, + ), Row( children: [ - const Icon(Icons.notifications_none_rounded, color: Colors.black), + Icon( + Icons.notifications_none_rounded, + color: isDark + ? Theme.of(context).colorScheme.surface + : Colors.black, + ), const SizedBox(width: 15), const CircleAvatar( radius: 20, @@ -63,7 +74,12 @@ class HomeScreen extends StatelessWidget { ), const SizedBox(width: 10), IconButton( - icon: const Icon(Icons.add_rounded, color: Colors.black), + icon: Icon( + Icons.add_rounded, + color: isDark + ? Theme.of(context).colorScheme.surface + : Colors.black, + ), onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => const CreateTaskScreen())), ), ], @@ -75,7 +91,13 @@ class HomeScreen extends StatelessWidget { Container( width: double.infinity, margin: const EdgeInsets.symmetric(horizontal: 20), - decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(30)), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: Theme.of(context).colorScheme.outline) + : null, + ), child: Padding( padding: const EdgeInsets.all(25.0), child: Column( @@ -129,7 +151,10 @@ class HomeScreen extends StatelessWidget { left: 30, child: Container( padding: const EdgeInsets.all(4), - decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, + shape: BoxShape.circle, + ), child: Icon( Icons.add_rounded, size: 20, @@ -144,7 +169,12 @@ class HomeScreen extends StatelessWidget { task: task2, // Truyền task2 vào đây leading: Container( padding: const EdgeInsets.all(12), - decoration: BoxDecoration(color: const Color(0xFFF1F7FD), borderRadius: BorderRadius.circular(15)), + decoration: BoxDecoration( + color: isDark + ? Theme.of(context).colorScheme.surfaceContainerHighest + : const Color(0xFFF1F7FD), + borderRadius: BorderRadius.circular(15), + ), child: Icon( Icons.call_outlined, color: Theme.of(context).colorScheme.primary, diff --git a/src/lib/features/tasks/view/screens/task_detail_screen.dart b/src/lib/features/tasks/view/screens/task_detail_screen.dart index b4dc17b..aa81264 100644 --- a/src/lib/features/tasks/view/screens/task_detail_screen.dart +++ b/src/lib/features/tasks/view/screens/task_detail_screen.dart @@ -50,7 +50,10 @@ class _TaskDetailScreenState extends State { // Show success message ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Task updated successfully!'), backgroundColor: Colors.green), + SnackBar( + content: const Text('Task updated successfully!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), ); // Return to the previous screen @@ -61,6 +64,7 @@ class _TaskDetailScreenState extends State { Widget build(BuildContext context) { // Format date for display String formattedDate = DateFormat('EEEE, d MMMM').format(widget.task.date); + final isDark = Theme.of(context).brightness == Brightness.dark; // Mock categories (Fetch from database later) List categories = ['Development', 'Research', 'Design', 'Backend']; @@ -71,10 +75,19 @@ class _TaskDetailScreenState extends State { backgroundColor: Colors.transparent, elevation: 0, leading: IconButton( - icon: const Icon(Icons.arrow_back_ios_new_rounded, color: Colors.black), + icon: Icon( + Icons.arrow_back_ios_new_rounded, + color: Theme.of(context).colorScheme.onSurface, + ), onPressed: () => Navigator.pop(context), ), - title: const Text('Task Details', style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold)), + title: Text( + 'Task Details', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurface, + fontWeight: FontWeight.bold, + ), + ), centerTitle: true, ), body: SafeArea( @@ -85,8 +98,11 @@ class _TaskDetailScreenState extends State { child: Container( margin: const EdgeInsets.all(20), decoration: BoxDecoration( - color: Colors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: Theme.of(context).colorScheme.outline) + : null, boxShadow: [ BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 10, offset: const Offset(0, 5)) ], @@ -119,7 +135,9 @@ class _TaskDetailScreenState extends State { onSelected: (selected) { if (selected) setState(() => _currentCategory = categories[index]); }, - backgroundColor: const Color(0xFFF1F7FD), + backgroundColor: isDark + ? Theme.of(context).colorScheme.surfaceContainerHighest + : const Color(0xFFF1F7FD), selectedColor: Theme.of(context).colorScheme.primary, labelStyle: TextStyle( color: isSelected @@ -129,7 +147,12 @@ class _TaskDetailScreenState extends State { ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), - side: const BorderSide(color: Color(0xFFF1F7FD), width: 1)), + side: BorderSide( + color: isDark + ? Theme.of(context).colorScheme.outline + : const Color(0xFFF1F7FD), + width: 1, + )), showCheckmark: false, ), ); @@ -141,7 +164,14 @@ class _TaskDetailScreenState extends State { // Display Task Date Text('Date', style: Theme.of(context).textTheme.labelLarge), const SizedBox(height: 5), - Text(formattedDate, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black)), + Text( + formattedDate, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), const SizedBox(height: 25), // Time Pickers for Start and End time diff --git a/src/lib/features/tasks/view/widgets/task_widgets.dart b/src/lib/features/tasks/view/widgets/task_widgets.dart index 9b1cc75..426d182 100644 --- a/src/lib/features/tasks/view/widgets/task_widgets.dart +++ b/src/lib/features/tasks/view/widgets/task_widgets.dart @@ -38,6 +38,7 @@ class DateBox extends StatelessWidget { Widget build(BuildContext context) { String day = DateFormat('d').format(date); String weekday = DateFormat('E').format(date).toUpperCase(); + final isDark = Theme.of(context).brightness == Brightness.dark; return Container( width: 55, @@ -47,7 +48,12 @@ class DateBox extends StatelessWidget { ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(20), - border: Border.all(color: Colors.grey.shade300, width: 1), + border: Border.all( + color: isDark + ? Theme.of(context).colorScheme.outline + : Colors.grey.shade300, + width: 1, + ), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -56,7 +62,9 @@ class DateBox extends StatelessWidget { style: TextStyle( fontSize: 22, fontWeight: FontWeight.bold, - color: isSelected ? Colors.white : Colors.black)), + color: isSelected + ? Colors.white + : Theme.of(context).colorScheme.onSurface)), const SizedBox(height: 5), Text(weekday, style: TextStyle( @@ -186,8 +194,11 @@ class TimePickerWidget extends StatelessWidget { Row( children: [ Text(formattedTime, - style: const TextStyle( - fontSize: 18, fontWeight: FontWeight.bold)), + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + )), const SizedBox(width: 5), Icon( Icons.keyboard_arrow_down_rounded, @@ -197,7 +208,7 @@ class TimePickerWidget extends StatelessWidget { ], ), const SizedBox(height: 5), - Container(height: 1, color: Colors.black26) + Container(height: 1, color: Theme.of(context).colorScheme.outline) ], ), ); diff --git a/src/lib/main.dart b/src/lib/main.dart index f9ab4e5..bcdb6be 100644 --- a/src/lib/main.dart +++ b/src/lib/main.dart @@ -55,7 +55,7 @@ class TaskApp extends StatelessWidget { themeMode: themeProvider.themeMode, theme: AppTheme.lightTheme, // Bộ màu sáng ông vừa map xong darkTheme: AppTheme.darkTheme, - home: const LoginView(), + home: const MainScreen(), debugShowCheckedModeBanner: false, ); } From b28e951ad56d0fe866ab09b07c65f1d48e27bf85 Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Mon, 13 Apr 2026 18:41:44 +0700 Subject: [PATCH 07/11] feat(RPC): update RPC to get data for heatmap --- .../features/user/service/user_service.dart | 7 ++ .../features/user/view/user_profile_view.dart | 110 ++++++++++++++++-- .../viewmodel/user_profile_viewmodel.dart | 8 +- src/pubspec.lock | 8 ++ src/pubspec.yaml | 1 + 5 files changed, 124 insertions(+), 10 deletions(-) diff --git a/src/lib/features/user/service/user_service.dart b/src/lib/features/user/service/user_service.dart index 9a6c0d7..c38a2db 100644 --- a/src/lib/features/user/service/user_service.dart +++ b/src/lib/features/user/service/user_service.dart @@ -8,7 +8,14 @@ class UserService { Future fetchUserProfile() async { // Mimic API call delay for smooth state switching try{ + final user = _supabase.auth.currentUser; + if (user == null) { + throw Exception("Không tìm thấy phiên đăng nhập. Hãy đăng nhập lại"); + } final response = await _supabase.rpc('get_user_profile_stats'); + if(response == null){ + throw Exception("Không thể lấy thông tin người dùng. Hãy thử lại sau"); + } response['id'] = _supabase.auth.currentUser!.id; return UserProfileModel.fromJson(response); } diff --git a/src/lib/features/user/view/user_profile_view.dart b/src/lib/features/user/view/user_profile_view.dart index 2e71926..18cf3cc 100644 --- a/src/lib/features/user/view/user_profile_view.dart +++ b/src/lib/features/user/view/user_profile_view.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import 'package:flutter_heatmap_calendar/flutter_heatmap_calendar.dart'; import '../viewmodel/user_profile_viewmodel.dart'; import 'widgets/profile_header.dart'; import 'widgets/stat_card.dart'; @@ -44,7 +45,7 @@ class UserProfileView extends StatelessWidget { duration: const Duration(milliseconds: 300), child: vm.isLoading ? Center( - key: ValueKey('loading'), + key: const ValueKey('loading'), child: CircularProgressIndicator( color: Theme.of(context).colorScheme.primary, ), @@ -55,11 +56,11 @@ class UserProfileView extends StatelessWidget { child: Text("Error loading profile"), ) : Builder( - builder: (innerContext) { - vm.syncThemeWithProfile(innerContext); - return _buildProfileContent(innerContext, vm); - }, - ), + builder: (innerContext) { + vm.syncThemeWithProfile(innerContext); + return _buildProfileContent(innerContext, vm); + }, + ), ); }, ), @@ -93,7 +94,7 @@ class UserProfileView extends StatelessWidget { child: StatCard( value: user.streaks.toString(), label: 'Streaks', - onTap: () {}, + onTap: () => _showHeatmapBottomSheet(context), ), ), ], @@ -114,7 +115,7 @@ class UserProfileView extends StatelessWidget { activeColor: Theme.of(context).colorScheme.surface, activeTrackColor: Theme.of(context).colorScheme.primary, inactiveThumbColor: - Theme.of(context).colorScheme.onSurfaceVariant, + Theme.of(context).colorScheme.onSurfaceVariant, inactiveTrackColor: Theme.of(context).colorScheme.outline, onChanged: (val) => vm.toggleNotification(val), ), @@ -153,4 +154,97 @@ class UserProfileView extends StatelessWidget { ), ); } + + void _showHeatmapBottomSheet(BuildContext context) { + // mock data for testing + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + + final Map mockHeatmapData = { + today.subtract(const Duration(days: 1)): 3, + today.subtract(const Duration(days: 2)): 7, + today.subtract(const Duration(days: 3)): 4, + today.subtract(const Duration(days: 4)): 8, + today.subtract(const Duration(days: 5)): 2, + today.subtract(const Duration(days: 8)): 5, + }; + + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Theme.of(context).colorScheme.surface, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + builder: (bottomSheetContext) { + return SafeArea( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Container( + width: 40, + height: 4, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.outline, + borderRadius: BorderRadius.circular(2), + ), + ), + ), + const SizedBox(height: 24), + + Text( + 'Bản đồ hoạt động', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + const SizedBox(height: 8), + Text( + 'Giữ vững phong độ nhé! 🔥', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 24), + + Center( + child: HeatMap( + datasets: mockHeatmapData, + colorMode: ColorMode.opacity, + showText: false, + scrollable: true, + size: 30, + + colorsets: { + 1: Theme.of(context).colorScheme.primary.withValues(alpha: 0.2), + 3: Theme.of(context).colorScheme.primary.withValues(alpha: 0.4), + 5: Theme.of(context).colorScheme.primary.withValues(alpha: 0.6), + 7: Theme.of(context).colorScheme.primary.withValues(alpha: 0.8), + 9: Theme.of(context).colorScheme.primary, + }, + onClick: (value) { + // Khi bấm vào 1 ô vuông, hiện số task hoàn thành ngày đó + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Đã hoàn thành $value công việc'), + behavior: SnackBarBehavior.floating, + ), + ); + }, + ), + ), + const SizedBox(height: 16), + ], + ), + ), + ); + }, + ); + } } \ No newline at end of file diff --git a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart index 21b28c0..1e6e8cf 100644 --- a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart +++ b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart @@ -36,7 +36,12 @@ class UserProfileViewModel extends ChangeNotifier { _lastAppliedAppearance = null; } catch (e) { debugPrint("Error loading profile: $e"); - _user = _buildMockUser(); + if(useMockData){ + _user = _buildMockUser(); + } + else{ + _user = null; + } } finally { _isLoading = false; notifyListeners(); @@ -47,7 +52,6 @@ class UserProfileViewModel extends ChangeNotifier { return UserProfileModel( id: 'mock-user-001', name: 'Alex Thompson', - // Valid URL so profile header can test normal network-avatar path. avatarUrl: 'https://i.pravatar.cc/300?img=12', appearance: 'Dark', tasksDone: 24, diff --git a/src/pubspec.lock b/src/pubspec.lock index 1b845aa..8802bd2 100644 --- a/src/pubspec.lock +++ b/src/pubspec.lock @@ -198,6 +198,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.0.0" + flutter_heatmap_calendar: + dependency: "direct main" + description: + name: flutter_heatmap_calendar + sha256: "0933071844cd604b938e38358984244292ba1ba8f4b4b6f0f091f5927a23e958" + url: "https://pub.dev" + source: hosted + version: "1.0.5" flutter_lints: dependency: "direct dev" description: diff --git a/src/pubspec.yaml b/src/pubspec.yaml index 65c8e9c..079d5ac 100644 --- a/src/pubspec.yaml +++ b/src/pubspec.yaml @@ -42,6 +42,7 @@ dependencies: flutter_ringtone_player: ^4.0.0+4 image_picker: ^1.2.1 shared_preferences: ^2.2.2 + flutter_heatmap_calendar: ^1.0.5 dev_dependencies: flutter_test: From 50d7848d45908b41c09cedfbaf0fda2a6d67dabb Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Mon, 13 Apr 2026 18:42:14 +0700 Subject: [PATCH 08/11] feat(RPC): update new RPC to get data for heatmap --- ...20260409084009_create_user_profile_rpc.sql | 2 +- ...1_update_user_profile_with_heatmap_rpc.sql | 66 +++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 supabase/migrations/20260413084521_update_user_profile_with_heatmap_rpc.sql diff --git a/supabase/migrations/20260409084009_create_user_profile_rpc.sql b/supabase/migrations/20260409084009_create_user_profile_rpc.sql index 235c129..cfc71d1 100644 --- a/supabase/migrations/20260409084009_create_user_profile_rpc.sql +++ b/supabase/migrations/20260409084009_create_user_profile_rpc.sql @@ -1,7 +1,7 @@ CREATE OR REPLACE FUNCTION get_user_profile_stats() RETURNS JSON LANGUAGE plpgsql -SECURITY INVOKER -- Chạy với quyền của user hiện tại (Tôn trọng RLS) +SECURITY INVOKER AS $$ DECLARE v_user_id UUID; diff --git a/supabase/migrations/20260413084521_update_user_profile_with_heatmap_rpc.sql b/supabase/migrations/20260413084521_update_user_profile_with_heatmap_rpc.sql new file mode 100644 index 0000000..aa82198 --- /dev/null +++ b/supabase/migrations/20260413084521_update_user_profile_with_heatmap_rpc.sql @@ -0,0 +1,66 @@ +CREATE OR REPLACE FUNCTION get_user_profile_stats(p_days INT DEFAULT 90) +RETURNS JSON +LANGUAGE plpgsql +SECURITY INVOKER +AS $$ +DECLARE + v_user_id UUID; + v_username TEXT; + v_avatar TEXT; + v_tasks_done INT; + v_current_streak INT; + v_heatmap_data JSON; +BEGIN + v_user_id := auth.uid(); + + IF v_user_id IS NULL THEN + RAISE EXCEPTION 'User not authenticated'; + END IF; + + SELECT username, avatar INTO v_username, v_avatar + FROM public.profile + WHERE id = v_user_id; + + SELECT COUNT(*) INTO v_tasks_done + FROM public.task + WHERE profile_id = v_user_id AND status = 1; + + -- Get task done per day for heatmap + SELECT json_object_agg(task_date::TEXT, task_count) INTO v_heatmap_data + FROM ( + SELECT DATE(updated_at AT TIME ZONE 'Asia/Ho_Chi_Minh') AS task_date, COUNT(*) AS task_count + FROM public.task + WHERE profile_id = v_user_id AND status = 1 + AND updated_at >= ((CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Ho_Chi_Minh')::DATE - (p_days || ' days')::INTERVAL) + GROUP BY DATE(updated_at AT TIME ZONE 'Asia/Ho_Chi_Minh') + ) t; + + WITH completed_dates AS ( + SELECT DISTINCT DATE(updated_at AT TIME ZONE 'Asia/Ho_Chi_Minh') AS task_date + FROM public.task + WHERE profile_id = v_user_id AND status = 1 + ), + streak_groups AS ( + SELECT task_date, + task_date - (ROW_NUMBER() OVER (ORDER BY task_date))::INT AS grp + FROM completed_dates + ), + streak_counts AS ( + SELECT grp, MAX(task_date) as end_date, COUNT(*) as streak_length + FROM streak_groups + GROUP BY grp + ) + SELECT COALESCE(MAX(streak_length), 0) INTO v_current_streak + FROM streak_counts + WHERE end_date >= ((CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Ho_Chi_Minh')::DATE - INTERVAL '1 day'); + + + RETURN json_build_object( + 'name', COALESCE(v_username, 'Unknown User'), + 'avatarUrl', COALESCE(v_avatar, ''), + 'tasksDone', COALESCE(v_tasks_done, 0), + 'streaks', COALESCE(v_current_streak, 0), + 'heatmapData', COALESCE(v_heatmap_data, '{}'::JSON) + ); +END; +$$; \ No newline at end of file From 8fb4d36267abb83d2679bca144fd3742d3cfa734 Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Fri, 17 Apr 2026 12:54:47 +0700 Subject: [PATCH 09/11] feat: integrate chatbot assistant --- .../chatbot/model/chatmessage_model.dart | 46 ++++++ .../chatbot/services/chatbot_services.dart | 44 ++++++ .../features/chatbot/view/chatbot_view.dart | 133 ++++++++++++++++++ .../chatbot/view/widgets/bot_avatar.dart | 28 ++++ .../chatbot/view/widgets/chat_header.dart | 50 +++++++ .../chatbot/view/widgets/day_separator.dart | 29 ++++ .../view/widgets/message_composer.dart | 92 ++++++++++++ .../chatbot/view/widgets/message_tile.dart | 122 ++++++++++++++++ .../view/widgets/typing_indicator.dart | 33 +++++ .../chatbot/view/widgets/user_avatar.dart | 47 +++++++ .../chatbot/viewmodel/chatbot_viewmodel.dart | 90 ++++++++++++ .../main/view/screens/main_screen.dart | 5 +- .../user/model/user_profile_model.dart | 43 ++++-- .../features/user/view/user_profile_view.dart | 78 +++++----- .../viewmodel/user_profile_viewmodel.dart | 35 +++-- src/pubspec.lock | 8 ++ src/pubspec.yaml | 1 + 17 files changed, 820 insertions(+), 64 deletions(-) create mode 100644 src/lib/features/chatbot/model/chatmessage_model.dart create mode 100644 src/lib/features/chatbot/services/chatbot_services.dart create mode 100644 src/lib/features/chatbot/view/chatbot_view.dart create mode 100644 src/lib/features/chatbot/view/widgets/bot_avatar.dart create mode 100644 src/lib/features/chatbot/view/widgets/chat_header.dart create mode 100644 src/lib/features/chatbot/view/widgets/day_separator.dart create mode 100644 src/lib/features/chatbot/view/widgets/message_composer.dart create mode 100644 src/lib/features/chatbot/view/widgets/message_tile.dart create mode 100644 src/lib/features/chatbot/view/widgets/typing_indicator.dart create mode 100644 src/lib/features/chatbot/view/widgets/user_avatar.dart create mode 100644 src/lib/features/chatbot/viewmodel/chatbot_viewmodel.dart diff --git a/src/lib/features/chatbot/model/chatmessage_model.dart b/src/lib/features/chatbot/model/chatmessage_model.dart new file mode 100644 index 0000000..2fb31ae --- /dev/null +++ b/src/lib/features/chatbot/model/chatmessage_model.dart @@ -0,0 +1,46 @@ +import 'dart:convert'; + +class ChatMessageModel { + final String text; + final bool isUser; + final DateTime timestamp; + + ChatMessageModel({ + required this.text, + required this.isUser, + DateTime? timestamp, + }) : timestamp = timestamp ?? DateTime.now(); + + factory ChatMessageModel.fromJson(Map json) { + final parsedTimestamp = + DateTime.tryParse(json['timestamp']?.toString() ?? '') ?? DateTime.now(); + + return ChatMessageModel( + text: json['text']?.toString() ?? '', + isUser: json['isUser'] as bool? ?? true, + timestamp: parsedTimestamp, + ); + } + + Map toJson() { + return { + 'text': text, + 'isUser': isUser, + 'timestamp': timestamp.toIso8601String(), + }; + } + + static String encodeList(List messages) { + return jsonEncode(messages.map((message) => message.toJson()).toList()); + } + + static List decodeList(String raw) { + final decoded = jsonDecode(raw); + if (decoded is! List) return []; + + return decoded + .whereType() + .map((item) => ChatMessageModel.fromJson(Map.from(item))) + .toList(); + } +} diff --git a/src/lib/features/chatbot/services/chatbot_services.dart b/src/lib/features/chatbot/services/chatbot_services.dart new file mode 100644 index 0000000..4845e6e --- /dev/null +++ b/src/lib/features/chatbot/services/chatbot_services.dart @@ -0,0 +1,44 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:google_generative_ai/google_generative_ai.dart'; + +class ChatBotAssistantService { + final String _apiKey = (dotenv.env['GEMINI_API_KEY'] ?? '').trim(); + GenerativeModel? _model; + ChatSession? _chatSession; + + ChatBotAssistantService() { + if (_apiKey.isEmpty) { + debugPrint("Forget to set GEMINI_API_KEY in .env file"); + return; + } + + _model = GenerativeModel( + apiKey: _apiKey, + model: 'gemini-2.5-flash', + systemInstruction: Content.system( + 'Bạn là một chuyên gia quản lý thời gian và trợ lý năng suất cho ứng dụng Task Management. ' + 'Nhiệm vụ của bạn là đưa ra lời khuyên ngắn gọn (dưới 100 chữ), thực tế để giúp người dùng ' + 'hoàn thành công việc. Trả lời bằng tiếng Việt thân thiện, nhiệt tình. ' + 'Từ chối mọi câu hỏi không liên quan đến công việc hoặc quản lý thời gian.', + ), + ); + + _chatSession = _model!.startChat(); + } + + Future sendMessage(String userMessage) async { + if (_chatSession == null) { + return 'Chatbot chưa được cấu hình API key. Vui lòng kiểm tra file .env.'; + } + + try { + final response = await _chatSession!.sendMessage( + Content.text(userMessage), + ); + return response.text ?? 'Xin lỗi, trợ lý đang bận xíu. Thử lại sau nhé!'; + } catch (e) { + return 'Lỗi kết nối AI: $e'; + } + } +} diff --git a/src/lib/features/chatbot/view/chatbot_view.dart b/src/lib/features/chatbot/view/chatbot_view.dart new file mode 100644 index 0000000..f5e104a --- /dev/null +++ b/src/lib/features/chatbot/view/chatbot_view.dart @@ -0,0 +1,133 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/chat_header.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/day_separator.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/message_composer.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/message_tile.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/typing_indicator.dart'; + +import '../viewmodel/chatbot_viewmodel.dart'; + +class ChatBotView extends StatelessWidget { + const ChatBotView({super.key, this.userAvatarUrl}); + + final String? userAvatarUrl; + + @override + Widget build(BuildContext context) { + return ChangeNotifierProvider( + create: (_) => ChatBotViewModel(), + child: _ChatBotViewBody(userAvatarUrl: userAvatarUrl), + ); + } +} + +class _ChatBotViewBody extends StatefulWidget { + const _ChatBotViewBody({this.userAvatarUrl}); + + final String? userAvatarUrl; + + @override + State<_ChatBotViewBody> createState() => _ChatBotViewBodyState(); +} + +class _ChatBotViewBodyState extends State<_ChatBotViewBody> { + final TextEditingController _controller = TextEditingController(); + final ScrollController _scrollController = ScrollController(); + + void _scrollToBottom() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (_scrollController.hasClients) { + _scrollController.animateTo( + _scrollController.position.maxScrollExtent, + duration: const Duration(milliseconds: 300), + curve: Curves.easeOut, + ); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + _scrollController.dispose(); + super.dispose(); + } + + Future _sendMessage(ChatBotViewModel viewModel) async { + final text = _controller.text.trim(); + if (text.isEmpty || viewModel.isLoading) return; + + _controller.clear(); + _scrollToBottom(); + + await viewModel.sendMessage(text); + if (!mounted) return; + + _scrollToBottom(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + return Scaffold( + backgroundColor: theme.scaffoldBackgroundColor, + body: SafeArea( + child: Column( + children: [ + const ChatHeader(), + Divider(height: 1, color: scheme.outline.withValues(alpha: 0.4)), + Expanded( + child: Consumer( + builder: (context, viewModel, _) { + return ListView.builder( + controller: _scrollController, + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 14, + ), + itemCount: viewModel.messages.length + 1, + itemBuilder: (context, index) { + if (index == 0) { + return const Padding( + padding: EdgeInsets.only(bottom: 16), + child: DaySeparator(label: 'Today'), + ); + } + + final message = viewModel.messages[index - 1]; + return MessageTile( + message: message, + userAvatarUrl: widget.userAvatarUrl, + ); + }, + ); + }, + ), + ), + Consumer( + builder: (context, viewModel, _) { + if (!viewModel.isLoading) return const SizedBox.shrink(); + return const Padding( + padding: EdgeInsets.fromLTRB(16, 0, 16, 12), + child: TypingIndicator(), + ); + }, + ), + Consumer( + builder: (context, viewModel, _) { + return MessageComposer( + controller: _controller, + isSending: viewModel.isLoading, + onSend: () => _sendMessage(viewModel), + ); + }, + ), + ], + ), + ), + ); + } +} diff --git a/src/lib/features/chatbot/view/widgets/bot_avatar.dart b/src/lib/features/chatbot/view/widgets/bot_avatar.dart new file mode 100644 index 0000000..d689144 --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/bot_avatar.dart @@ -0,0 +1,28 @@ +import 'package:flutter/material.dart'; + +class BotAvatar extends StatelessWidget { + const BotAvatar({super.key, required this.size}); + + final double size; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + + return Container( + width: size, + height: size, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: scheme.surfaceContainerHighest, + ), + alignment: Alignment.center, + child: Icon( + Icons.smart_toy_rounded, + size: size * 0.58, + color: scheme.primary, + ), + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/chat_header.dart b/src/lib/features/chatbot/view/widgets/chat_header.dart new file mode 100644 index 0000000..b721e1f --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/chat_header.dart @@ -0,0 +1,50 @@ +import 'package:flutter/material.dart'; + +import 'bot_avatar.dart'; + +class ChatHeader extends StatelessWidget { + const ChatHeader({super.key}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + return Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 10), + child: Row( + children: [ + const BotAvatar(size: 48), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'TaskBot', + style: theme.textTheme.headlineSmall?.copyWith( + color: scheme.primary, + fontWeight: FontWeight.w800, + ), + ), + Text( + 'ONLINE AI ASSISTANT', + style: theme.textTheme.labelLarge?.copyWith( + color: scheme.tertiary, + letterSpacing: 0.6, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + IconButton( + onPressed: () {}, + icon: Icon(Icons.settings, color: scheme.onSurfaceVariant), + ), + ], + ), + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/day_separator.dart b/src/lib/features/chatbot/view/widgets/day_separator.dart new file mode 100644 index 0000000..351c129 --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/day_separator.dart @@ -0,0 +1,29 @@ +import 'package:flutter/material.dart'; + +class DaySeparator extends StatelessWidget { + const DaySeparator({super.key, required this.label}); + + final String label; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest.withValues(alpha: 0.7), + borderRadius: BorderRadius.circular(20), + ), + child: Text( + label, + style: TextStyle( + color: scheme.onSurfaceVariant, + fontWeight: FontWeight.w600, + ), + ), + ), + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/message_composer.dart b/src/lib/features/chatbot/view/widgets/message_composer.dart new file mode 100644 index 0000000..7b4988f --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/message_composer.dart @@ -0,0 +1,92 @@ +import 'package:flutter/material.dart'; + +class MessageComposer extends StatelessWidget { + const MessageComposer({ + super.key, + required this.controller, + required this.onSend, + required this.isSending, + }); + + final TextEditingController controller; + final VoidCallback onSend; + final bool isSending; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + return SafeArea( + minimum: const EdgeInsets.fromLTRB(16, 0, 16, 14), + child: Container( + decoration: BoxDecoration( + color: scheme.surface, + borderRadius: BorderRadius.circular(22), + boxShadow: [ + BoxShadow( + color: scheme.shadow.withValues(alpha: 0.14), + blurRadius: 14, + offset: const Offset(0, 4), + ), + ], + ), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + child: Row( + children: [ + IconButton( + constraints: const BoxConstraints.tightFor(width: 40, height: 40), + padding: EdgeInsets.zero, + onPressed: () {}, + icon: Icon(Icons.add_circle, color: scheme.onSurfaceVariant), + ), + const SizedBox(width: 6), + Expanded( + child: TextField( + controller: controller, + textInputAction: TextInputAction.send, + enabled: !isSending, + onSubmitted: (_) => onSend(), + style: TextStyle(color: scheme.onSurface), + decoration: InputDecoration( + hintText: 'Type a message or ask for help...', + hintStyle: TextStyle(color: scheme.onSurfaceVariant), + border: InputBorder.none, + ), + ), + ), + IconButton( + constraints: const BoxConstraints.tightFor(width: 40, height: 40), + padding: EdgeInsets.zero, + onPressed: () {}, + icon: Icon(Icons.mic, color: scheme.onSurfaceVariant), + ), + const SizedBox(width: 6), + SizedBox( + width: 44, + height: 44, + child: ElevatedButton( + onPressed: isSending ? null : onSend, + style: ElevatedButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + ), + padding: EdgeInsets.zero, + backgroundColor: scheme.primary, + foregroundColor: scheme.onPrimary, + ), + child: Icon( + Icons.send_rounded, + color: isSending + ? scheme.onPrimary.withValues(alpha: 0.7) + : scheme.onPrimary, + ), + ), + ), + ], + ), + ), + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/message_tile.dart b/src/lib/features/chatbot/view/widgets/message_tile.dart new file mode 100644 index 0000000..74546a2 --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/message_tile.dart @@ -0,0 +1,122 @@ +import 'package:flutter/material.dart'; + +import '../../model/chatmessage_model.dart'; +import 'bot_avatar.dart'; +import 'user_avatar.dart'; + +class MessageTile extends StatelessWidget { + const MessageTile({super.key, required this.message, this.userAvatarUrl}); + + final ChatMessageModel message; + final String? userAvatarUrl; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final isUser = message.isUser; + final crossAxis = isUser ? CrossAxisAlignment.end : CrossAxisAlignment.start; + + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: LayoutBuilder( + builder: (context, constraints) { + final maxBubbleWidth = constraints.maxWidth * 0.72; + + Widget bubble() { + return ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxBubbleWidth), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + decoration: BoxDecoration( + color: isUser ? scheme.primary : scheme.surface, + borderRadius: BorderRadius.circular(20), + boxShadow: [ + BoxShadow( + color: scheme.shadow.withValues(alpha: 0.12), + blurRadius: 10, + offset: const Offset(0, 3), + ), + ], + ), + child: Text( + _breakLongTokens(message.text), + softWrap: true, + style: theme.textTheme.titleMedium?.copyWith( + height: 1.45, + color: isUser ? scheme.onPrimary : scheme.onSurface, + ), + ), + ), + ); + } + + return Column( + crossAxisAlignment: crossAxis, + children: [ + if (isUser) + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Align( + alignment: Alignment.centerRight, + child: bubble(), + ), + ), + const SizedBox(width: 10), + UserAvatar(size: 36, avatarUrl: userAvatarUrl), + ], + ) + else + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const BotAvatar(size: 36), + const SizedBox(width: 10), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: bubble(), + ), + ), + ], + ), + const SizedBox(height: 6), + Padding( + padding: EdgeInsets.only(left: isUser ? 0 : 46, right: isUser ? 46 : 0), + child: Text( + _formatTime(context, message.timestamp), + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ), + ], + ); + }, + ), + ); + } + + String _formatTime(BuildContext context, DateTime time) { + final localTime = TimeOfDay.fromDateTime(time); + return MaterialLocalizations.of(context).formatTimeOfDay(localTime); + } + + String _breakLongTokens(String input) { + final tokenRegex = RegExp(r'\S{24,}'); + return input.replaceAllMapped(tokenRegex, (match) { + final token = match.group(0) ?? ''; + final buffer = StringBuffer(); + for (int i = 0; i < token.length; i++) { + buffer.write(token[i]); + if ((i + 1) % 12 == 0 && i + 1 < token.length) { + buffer.write('\u200B'); + } + } + return buffer.toString(); + }); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/typing_indicator.dart b/src/lib/features/chatbot/view/widgets/typing_indicator.dart new file mode 100644 index 0000000..a35d7cc --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/typing_indicator.dart @@ -0,0 +1,33 @@ +import 'package:flutter/material.dart'; + +import 'bot_avatar.dart'; + +class TypingIndicator extends StatelessWidget { + const TypingIndicator({super.key}); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Row( + children: [ + const BotAvatar(size: 34), + const SizedBox(width: 10), + Flexible( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + decoration: BoxDecoration( + color: scheme.surface, + borderRadius: BorderRadius.circular(16), + ), + child: Text( + 'TaskBot is typing...', + overflow: TextOverflow.ellipsis, + style: TextStyle(color: scheme.onSurfaceVariant), + ), + ), + ), + ], + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/user_avatar.dart b/src/lib/features/chatbot/view/widgets/user_avatar.dart new file mode 100644 index 0000000..a8ae00b --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/user_avatar.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +class UserAvatar extends StatelessWidget { + const UserAvatar({super.key, required this.size, this.avatarUrl}); + + final double size; + final String? avatarUrl; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final fallbackUrl = + (Supabase.instance.client.auth.currentUser?.userMetadata?['avatar_url'] as String?)?.trim(); + final resolvedUrl = (avatarUrl ?? fallbackUrl ?? '').trim(); + final canLoadNetworkImage = _isValidHttpUrl(resolvedUrl); + + return Container( + width: size, + height: size, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: scheme.surfaceContainerHighest, + ), + clipBehavior: Clip.antiAlias, + child: canLoadNetworkImage + ? Image.network( + resolvedUrl, + fit: BoxFit.cover, + errorBuilder: (_, _, _) => Icon( + Icons.person, + size: size * 0.6, + color: scheme.primary, + ), + ) + : Icon(Icons.person, size: size * 0.6, color: scheme.primary), + ); + } + + bool _isValidHttpUrl(String value) { + if (value.isEmpty || value.length > 2048) return false; + final uri = Uri.tryParse(value); + if (uri == null) return false; + return uri.hasAbsolutePath && (uri.scheme == 'http' || uri.scheme == 'https'); + } +} + diff --git a/src/lib/features/chatbot/viewmodel/chatbot_viewmodel.dart b/src/lib/features/chatbot/viewmodel/chatbot_viewmodel.dart new file mode 100644 index 0000000..fd5a4d3 --- /dev/null +++ b/src/lib/features/chatbot/viewmodel/chatbot_viewmodel.dart @@ -0,0 +1,90 @@ +import 'package:flutter/foundation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../model/chatmessage_model.dart'; +import '../services/chatbot_services.dart'; + +class ChatBotViewModel extends ChangeNotifier { + static const String _historyKey = 'chatbot_history_v1'; + static const int _maxHistoryMessages = 200; + + final _aiService = ChatBotAssistantService(); + final List _messages = []; + + ChatBotViewModel() { + _loadHistory(); + } + + List _initialMessages() => [ + ChatMessageModel( + text: 'Chào bạn! Tôi là trợ lý năng suất. Hôm nay bạn cần tôi giúp gì?', + isUser: false, + ), + ]; + + List get messages => _messages; + + bool _isLoading = false; + + bool get isLoading => _isLoading; + + Future _loadHistory() async { + try { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(_historyKey); + + if (raw == null || raw.trim().isEmpty) { + _messages + ..clear() + ..addAll(_initialMessages()); + await _saveHistory(); + } else { + final storedMessages = ChatMessageModel.decodeList(raw); + _messages + ..clear() + ..addAll( + storedMessages.isEmpty ? _initialMessages() : storedMessages, + ); + } + } catch (e) { + debugPrint('Error loading chatbot history: $e'); + _messages + ..clear() + ..addAll(_initialMessages()); + } + + notifyListeners(); + } + + Future _saveHistory() async { + try { + final prefs = await SharedPreferences.getInstance(); + if (_messages.length > _maxHistoryMessages) { + _messages.removeRange(0, _messages.length - _maxHistoryMessages); + } + await prefs.setString( + _historyKey, + ChatMessageModel.encodeList(_messages), + ); + } catch (e) { + debugPrint('Error saving chatbot history: $e'); + } + } + + Future sendMessage(String text) async { + final normalizedText = text.trim(); + if (normalizedText.isEmpty) return; + + _messages.add(ChatMessageModel(text: normalizedText, isUser: true)); + _isLoading = true; + notifyListeners(); + await _saveHistory(); + + final response = await _aiService.sendMessage(normalizedText); + + _messages.add(ChatMessageModel(text: response, isUser: false)); + _isLoading = false; + await _saveHistory(); + notifyListeners(); + } +} diff --git a/src/lib/features/main/view/screens/main_screen.dart b/src/lib/features/main/view/screens/main_screen.dart index cb1c9d0..0ddd37b 100644 --- a/src/lib/features/main/view/screens/main_screen.dart +++ b/src/lib/features/main/view/screens/main_screen.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:task_management_app/features/statistics/viewmodel/statistics_viewmodel.dart'; import 'package:task_management_app/features/tasks/view/screens/home_screen.dart'; +import 'package:task_management_app/features/chatbot/view/chatbot_view.dart'; import 'settings_screen.dart'; import 'package:task_management_app/features/user/viewmodel/user_profile_viewmodel.dart'; import '../../../note/view/focus_screen.dart'; @@ -23,7 +24,7 @@ class _MainScreenState extends State { final List _screens = [ const Center(child: HomeScreen()), - const Center(child: Text('Màn hình Lịch')), + const ChatBotView(), ChangeNotifierProvider( create: (_) => FocusViewModel(), child: const FocusScreen(), @@ -63,7 +64,7 @@ class _MainScreenState extends State { mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ _buildNavItem(context, Icons.checklist_rounded, 'Công việc', 0), - _buildNavItem(context, Icons.calendar_today_rounded, 'Lịch', 1), + _buildNavItem(context, Icons.smart_toy_rounded, 'Chat', 1), _buildNavItem(context, Icons.timer_rounded, 'Tập trung', 2), _buildNavItem(context, Icons.bar_chart_rounded, 'Thống kê', 3), _buildNavItem(context, Icons.person_2_rounded, 'Cá nhân', 4), diff --git a/src/lib/features/user/model/user_profile_model.dart b/src/lib/features/user/model/user_profile_model.dart index d378b4b..6f0fd50 100644 --- a/src/lib/features/user/model/user_profile_model.dart +++ b/src/lib/features/user/model/user_profile_model.dart @@ -6,6 +6,7 @@ class UserProfileModel { final String avatarUrl; bool isNotificationEnabled; String appearance; + final Map heatmapData; UserProfileModel({ required this.id, @@ -15,6 +16,7 @@ class UserProfileModel { required this.avatarUrl, this.isNotificationEnabled = true, this.appearance = 'Light', + required this.heatmapData, }); factory UserProfileModel.fromJson(Map json) { @@ -25,25 +27,44 @@ class UserProfileModel { return 0; } + Map parseHeatmap = {}; + if (json['heatmapData'] != null) { + final Map rawHeatmap = json['heatmapData']; + rawHeatmap.forEach((dateString, count) { + try { + parseHeatmap[DateTime.parse(dateString)] = parseInt(count); + } catch (e) { + // skip error + } + }); + } return UserProfileModel( id: json['id'] as String? ?? '', name: (json['name'] ?? json['full_name'] ?? json['username']) as String? ?? - 'Unknown User', + 'Unknown User', tasksDone: parseInt(json['tasksDone'] ?? json['tasks_done']), streaks: parseInt(json['streaks'] ?? json['streak_count']), avatarUrl: - (json['avatarUrl'] ?? json['avatar_url'] ?? json['avatar']) as String? ?? - '', + (json['avatarUrl'] ?? json['avatar_url'] ?? json['avatar']) + as String? ?? + '', isNotificationEnabled: - (json['isNotificationEnabled'] ?? json['is_notification_enabled']) as bool? ?? - true, - appearance: (json['appearance'] ?? json['theme_mode']) as String? ?? 'Light', + (json['isNotificationEnabled'] ?? json['is_notification_enabled']) + as bool? ?? + true, + appearance: + (json['appearance'] ?? json['theme_mode']) as String? ?? 'Light', + + heatmapData: parseHeatmap, ); } - Map toJson() { + Map heatmapJson = {}; + heatmapData.forEach((date, count) { + heatmapJson[date.toIso8601String().split('T').first] = count; + }); return { 'id': id, 'name': name, @@ -52,6 +73,7 @@ class UserProfileModel { 'avatarUrl': avatarUrl, 'isNotificationEnabled': isNotificationEnabled, 'appearance': appearance, + 'heatmapData': heatmapJson, }; } @@ -63,6 +85,7 @@ class UserProfileModel { String? avatarUrl, bool? isNotificationEnabled, String? appearance, + Map? heatmapData, }) { return UserProfileModel( id: id ?? this.id, @@ -70,8 +93,10 @@ class UserProfileModel { tasksDone: tasksDone ?? this.tasksDone, streaks: streaks ?? this.streaks, avatarUrl: avatarUrl ?? this.avatarUrl, - isNotificationEnabled: isNotificationEnabled ?? this.isNotificationEnabled, + isNotificationEnabled: + isNotificationEnabled ?? this.isNotificationEnabled, appearance: appearance ?? this.appearance, + heatmapData: heatmapData ?? this.heatmapData, ); } -} \ No newline at end of file +} diff --git a/src/lib/features/user/view/user_profile_view.dart b/src/lib/features/user/view/user_profile_view.dart index 18cf3cc..1e57bd2 100644 --- a/src/lib/features/user/view/user_profile_view.dart +++ b/src/lib/features/user/view/user_profile_view.dart @@ -1,12 +1,13 @@ import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; import 'package:flutter_heatmap_calendar/flutter_heatmap_calendar.dart'; +import 'package:provider/provider.dart'; + import '../viewmodel/user_profile_viewmodel.dart'; +import 'widgets/logout_button.dart'; import 'widgets/profile_header.dart'; -import 'widgets/stat_card.dart'; -import 'widgets/settings_section.dart'; import 'widgets/settings_list_tile.dart'; -import 'widgets/logout_button.dart'; +import 'widgets/settings_section.dart'; +import 'widgets/stat_card.dart'; class UserProfileView extends StatelessWidget { const UserProfileView({super.key}); @@ -45,22 +46,22 @@ class UserProfileView extends StatelessWidget { duration: const Duration(milliseconds: 300), child: vm.isLoading ? Center( - key: const ValueKey('loading'), - child: CircularProgressIndicator( - color: Theme.of(context).colorScheme.primary, - ), - ) + key: const ValueKey('loading'), + child: CircularProgressIndicator( + color: Theme.of(context).colorScheme.primary, + ), + ) : vm.user == null ? const Center( - key: ValueKey('error'), - child: Text("Error loading profile"), - ) + key: ValueKey('error'), + child: Text("Error loading profile"), + ) : Builder( - builder: (innerContext) { - vm.syncThemeWithProfile(innerContext); - return _buildProfileContent(innerContext, vm); - }, - ), + builder: (innerContext) { + vm.syncThemeWithProfile(innerContext); + return _buildProfileContent(innerContext, vm); + }, + ), ); }, ), @@ -94,7 +95,7 @@ class UserProfileView extends StatelessWidget { child: StatCard( value: user.streaks.toString(), label: 'Streaks', - onTap: () => _showHeatmapBottomSheet(context), + onTap: () => _showHeatmapBottomSheet(context, vm), ), ), ], @@ -114,8 +115,9 @@ class UserProfileView extends StatelessWidget { value: user.isNotificationEnabled, activeColor: Theme.of(context).colorScheme.surface, activeTrackColor: Theme.of(context).colorScheme.primary, - inactiveThumbColor: - Theme.of(context).colorScheme.onSurfaceVariant, + inactiveThumbColor: Theme.of( + context, + ).colorScheme.onSurfaceVariant, inactiveTrackColor: Theme.of(context).colorScheme.outline, onChanged: (val) => vm.toggleNotification(val), ), @@ -155,20 +157,7 @@ class UserProfileView extends StatelessWidget { ); } - void _showHeatmapBottomSheet(BuildContext context) { - // mock data for testing - final now = DateTime.now(); - final today = DateTime(now.year, now.month, now.day); - - final Map mockHeatmapData = { - today.subtract(const Duration(days: 1)): 3, - today.subtract(const Duration(days: 2)): 7, - today.subtract(const Duration(days: 3)): 4, - today.subtract(const Duration(days: 4)): 8, - today.subtract(const Duration(days: 5)): 2, - today.subtract(const Duration(days: 8)): 5, - }; - + void _showHeatmapBottomSheet(BuildContext context, UserProfileViewModel vm) { showModalBottomSheet( context: context, isScrollControlled: true, @@ -215,21 +204,28 @@ class UserProfileView extends StatelessWidget { Center( child: HeatMap( - datasets: mockHeatmapData, + datasets: vm.user!.heatmapData, colorMode: ColorMode.opacity, showText: false, scrollable: true, size: 30, colorsets: { - 1: Theme.of(context).colorScheme.primary.withValues(alpha: 0.2), - 3: Theme.of(context).colorScheme.primary.withValues(alpha: 0.4), - 5: Theme.of(context).colorScheme.primary.withValues(alpha: 0.6), - 7: Theme.of(context).colorScheme.primary.withValues(alpha: 0.8), + 1: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.2), + 3: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.4), + 5: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.6), + 7: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.8), 9: Theme.of(context).colorScheme.primary, }, onClick: (value) { - // Khi bấm vào 1 ô vuông, hiện số task hoàn thành ngày đó ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Đã hoàn thành $value công việc'), @@ -247,4 +243,4 @@ class UserProfileView extends StatelessWidget { }, ); } -} \ No newline at end of file +} diff --git a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart index 1e6e8cf..3ba0c6c 100644 --- a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart +++ b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart @@ -1,6 +1,6 @@ import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; -import 'package:provider/provider.dart'; // Import thêm Provider import '../../../core/theme/theme_provider.dart'; import '../../auth/presentation/view/auth_gate.dart'; @@ -16,9 +16,11 @@ class UserProfileViewModel extends ChangeNotifier { UserProfileViewModel({this.useMockData = true}); UserProfileModel? _user; + UserProfileModel? get user => _user; bool _isLoading = true; + bool get isLoading => _isLoading; /// Load profile data @@ -36,10 +38,9 @@ class UserProfileViewModel extends ChangeNotifier { _lastAppliedAppearance = null; } catch (e) { debugPrint("Error loading profile: $e"); - if(useMockData){ + if (useMockData) { _user = _buildMockUser(); - } - else{ + } else { _user = null; } } finally { @@ -49,6 +50,17 @@ class UserProfileViewModel extends ChangeNotifier { } UserProfileModel _buildMockUser() { + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + + final Map mockHeatmapData = { + today.subtract(const Duration(days: 1)): 3, + today.subtract(const Duration(days: 2)): 7, + today.subtract(const Duration(days: 3)): 4, + today.subtract(const Duration(days: 4)): 8, + today.subtract(const Duration(days: 5)): 2, + today.subtract(const Duration(days: 8)): 5, + }; return UserProfileModel( id: 'mock-user-001', name: 'Alex Thompson', @@ -57,6 +69,7 @@ class UserProfileViewModel extends ChangeNotifier { tasksDone: 24, streaks: 12, isNotificationEnabled: true, + heatmapData: mockHeatmapData, ); } @@ -68,7 +81,6 @@ class UserProfileViewModel extends ChangeNotifier { } } - void updateAppearance(BuildContext context, String newAppearance) { if (_user != null) { _user!.appearance = newAppearance; @@ -76,7 +88,7 @@ class UserProfileViewModel extends ChangeNotifier { notifyListeners(); if (context.mounted) { - context.read().updateTheme(newAppearance); + context.read().updateTheme(newAppearance); } } } @@ -98,17 +110,16 @@ class UserProfileViewModel extends ChangeNotifier { if (context.mounted) { Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => const AuthGate()), - (route) => false, + (route) => false, ); } - } catch (e) { debugPrint("Lỗi đăng xuất: $e"); if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Lỗi đăng xuất: $e')), - ); + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Lỗi đăng xuất: $e'))); } } } -} \ No newline at end of file +} diff --git a/src/pubspec.lock b/src/pubspec.lock index 8802bd2..d8bd0bc 100644 --- a/src/pubspec.lock +++ b/src/pubspec.lock @@ -264,6 +264,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.3" + google_generative_ai: + dependency: "direct main" + description: + name: google_generative_ai + sha256: "71f613d0247968992ad87a0eb21650a566869757442ba55a31a81be6746e0d1f" + url: "https://pub.dev" + source: hosted + version: "0.4.7" gotrue: dependency: transitive description: diff --git a/src/pubspec.yaml b/src/pubspec.yaml index 079d5ac..9afc694 100644 --- a/src/pubspec.yaml +++ b/src/pubspec.yaml @@ -43,6 +43,7 @@ dependencies: image_picker: ^1.2.1 shared_preferences: ^2.2.2 flutter_heatmap_calendar: ^1.0.5 + google_generative_ai: ^0.4.7 dev_dependencies: flutter_test: From 67e0496a57d0d7116ca025514c48d950b4b1c2e2 Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Fri, 17 Apr 2026 14:56:08 +0700 Subject: [PATCH 10/11] feat(chatbot): integrate create task, answer question for chatbot --- .../chatbot/services/chatbot_services.dart | 72 +++++++++++++++++++ .../chatbot/view/widgets/chat_header.dart | 4 -- .../20260417060333_chatbot_add_task_rpc.sql | 52 ++++++++++++++ 3 files changed, 124 insertions(+), 4 deletions(-) create mode 100644 supabase/migrations/20260417060333_chatbot_add_task_rpc.sql diff --git a/src/lib/features/chatbot/services/chatbot_services.dart b/src/lib/features/chatbot/services/chatbot_services.dart index 4845e6e..70a4f78 100644 --- a/src/lib/features/chatbot/services/chatbot_services.dart +++ b/src/lib/features/chatbot/services/chatbot_services.dart @@ -1,6 +1,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:google_generative_ai/google_generative_ai.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; class ChatBotAssistantService { final String _apiKey = (dotenv.env['GEMINI_API_KEY'] ?? '').trim(); @@ -16,6 +17,37 @@ class ChatBotAssistantService { _model = GenerativeModel( apiKey: _apiKey, model: 'gemini-2.5-flash', + tools: [ + Tool( + functionDeclarations: [ + FunctionDeclaration( + 'create_task_full', + 'Tạo một công việc mới. Hãy tự động trích xuất tên công việc, suy luận độ ưu tiên (1-Thấp, 2-Trung bình, 3-Cao) và các thẻ (tags) dựa trên câu nói của người dùng.', + Schema( + SchemaType.object, + properties: { + 'title': Schema( + SchemaType.string, + description: 'Tên công việc cần làm', + ), + 'priority': Schema( + SchemaType.integer, + description: + 'Độ ưu tiên: 1 (Thấp), 2 (Trung bình), 3 (Cao). Nếu người dùng không nói rõ, mặc định là 1.', + ), + 'tags': Schema( + SchemaType.array, + items: Schema(SchemaType.string), + description: + 'Danh sách các thẻ phân loại (ví dụ: ["Học tập", "Gấp", "Backend"]). Gửi mảng rỗng [] nếu không có.', + ), + }, + requiredProperties: ['title', 'priority', 'tags'], + ), + ), + ], + ), + ], systemInstruction: Content.system( 'Bạn là một chuyên gia quản lý thời gian và trợ lý năng suất cho ứng dụng Task Management. ' 'Nhiệm vụ của bạn là đưa ra lời khuyên ngắn gọn (dưới 100 chữ), thực tế để giúp người dùng ' @@ -36,8 +68,48 @@ class ChatBotAssistantService { final response = await _chatSession!.sendMessage( Content.text(userMessage), ); + + if (response.functionCalls.isNotEmpty) { + final functionCall = response.functionCalls.first; + if (functionCall.name == 'create_task_full') { + final args = functionCall.args; + final title = args['title'] as String; + final priority = (args['priority'] as num?)?.toInt() ?? 1; + final rawTags = args['tags'] as List? ?? []; + final tags = rawTags.map((e) => e.toString()).toList(); + + final userId = Supabase.instance.client.auth.currentUser?.id; + if (userId == null) { + return 'Vui lòng đăng nhập để tạo công việc.'; + } + + final dbResponse = await Supabase.instance.client.rpc( + 'create_task_full', + params: { + 'p_title': title, + 'p_priority': priority, + 'p_profile_id': userId, + 'p_tag_names': tags, + }, + ); + + final isSuccess = dbResponse['success'] == true; + final functionResponse = await _chatSession!.sendMessage( + Content.functionResponse('create_task_full', { + 'status': isSuccess ? 'Thành công' : 'Thất bại', + }), + ); + return functionResponse.text ?? 'Đã xử lý xong yêu cầu của bạn!'; + } + } return response.text ?? 'Xin lỗi, trợ lý đang bận xíu. Thử lại sau nhé!'; } catch (e) { + final errorString = e.toString(); + if (errorString.contains('503')) { + return 'Bạn đợi vài phút rồi chat lại nhé!'; + } else if (errorString.contains('429')) { + return 'Bạn chat nhanh quá! Vui lòng chờ chút'; + } return 'Lỗi kết nối AI: $e'; } } diff --git a/src/lib/features/chatbot/view/widgets/chat_header.dart b/src/lib/features/chatbot/view/widgets/chat_header.dart index b721e1f..35e83ff 100644 --- a/src/lib/features/chatbot/view/widgets/chat_header.dart +++ b/src/lib/features/chatbot/view/widgets/chat_header.dart @@ -38,10 +38,6 @@ class ChatHeader extends StatelessWidget { ], ), ), - IconButton( - onPressed: () {}, - icon: Icon(Icons.settings, color: scheme.onSurfaceVariant), - ), ], ), ); diff --git a/supabase/migrations/20260417060333_chatbot_add_task_rpc.sql b/supabase/migrations/20260417060333_chatbot_add_task_rpc.sql new file mode 100644 index 0000000..197e189 --- /dev/null +++ b/supabase/migrations/20260417060333_chatbot_add_task_rpc.sql @@ -0,0 +1,52 @@ +CREATE OR REPLACE FUNCTION create_task_full( + p_title TEXT, + p_priority INT4, + p_profile_id UUID, + p_tag_names TEXT[] +) +RETURNS JSON +LANGUAGE plpgsql +AS $$ +DECLARE + v_task_id INT8; + v_tag_name TEXT; + v_tag_id INT8; +BEGIN + + INSERT INTO task (title, priority, profile_id, status) + VALUES (p_title, p_priority, p_profile_id, 0) + RETURNING id INTO v_task_id; + + IF p_tag_names IS NOT NULL THEN + FOREACH v_tag_name IN ARRAY p_tag_names + LOOP + v_tag_name := trim(v_tag_name); + + IF v_tag_name != '' THEN + INSERT INTO tag (name, profile_id, color_code) + VALUES (v_tag_name, p_profile_id, '#6200EE') + ON CONFLICT (name, profile_id) + DO UPDATE SET name = EXCLUDED.name + RETURNING id INTO v_tag_id; + + + INSERT INTO task_tags (task_id, tag_id) + VALUES (v_task_id, v_tag_id) + ON CONFLICT DO NOTHING; + END IF; + END LOOP; + END IF; + + RETURN json_build_object( + 'success', true, + 'task_id', v_task_id, + 'message', 'Đã tạo task với priority ' || p_priority + ); + +EXCEPTION WHEN OTHERS THEN + RETURN json_build_object( + 'success', false, + 'error', SQLERRM + ); +END; +$$; \ No newline at end of file From 6049bede39238343cef2d0d404bd0d524bb4ae47 Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Fri, 17 Apr 2026 20:56:34 +0700 Subject: [PATCH 11/11] feat: remove mock data and get data tags and categories from supabase --- .../core/utils/adaptive_color_extension.dart | 11 + .../category/model/category_model.dart | 52 ++++ .../repository/category_repository.dart | 26 ++ .../view/widgets/category_choice_chips.dart | 58 +++++ .../viewmodel/category_viewmodel.dart | 41 +++ .../main/view/screens/main_screen.dart | 68 +++-- .../view/screens/statistics_screen.dart | 5 + .../view/widgets/statistics_widgets.dart | 176 ++++++++++--- src/lib/features/tag/model/tag_model.dart | 52 ++++ .../tag/repository/tag_repository.dart | 45 ++++ .../tag/view/widgets/tag_selector.dart | 194 +++++++++++++++ .../features/tag/viewmodel/tag_viewmodel.dart | 113 +++++++++ src/lib/features/tasks/model/task_model.dart | 14 +- .../view/screens/create_task_screen.dart | 105 ++++---- .../view/screens/task_detail_screen.dart | 146 +++-------- .../tasks/view/widgets/tag_selector.dart | 233 +----------------- .../tasks/viewmodel/task_viewmodel.dart | 128 +--------- src/lib/main.dart | 8 + src/pubspec.lock | 16 +- 19 files changed, 902 insertions(+), 589 deletions(-) create mode 100644 src/lib/core/utils/adaptive_color_extension.dart create mode 100644 src/lib/features/category/model/category_model.dart create mode 100644 src/lib/features/category/repository/category_repository.dart create mode 100644 src/lib/features/category/view/widgets/category_choice_chips.dart create mode 100644 src/lib/features/category/viewmodel/category_viewmodel.dart create mode 100644 src/lib/features/tag/model/tag_model.dart create mode 100644 src/lib/features/tag/repository/tag_repository.dart create mode 100644 src/lib/features/tag/view/widgets/tag_selector.dart create mode 100644 src/lib/features/tag/viewmodel/tag_viewmodel.dart diff --git a/src/lib/core/utils/adaptive_color_extension.dart b/src/lib/core/utils/adaptive_color_extension.dart new file mode 100644 index 0000000..f5c022e --- /dev/null +++ b/src/lib/core/utils/adaptive_color_extension.dart @@ -0,0 +1,11 @@ +import 'package:flutter/material.dart'; + +extension AdaptiveColorExtension on Color { + Color toAdaptiveColor(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + if (!isDark) return this; + + return Color.lerp(this, Colors.white, 0.4) ?? this; + } +} + diff --git a/src/lib/features/category/model/category_model.dart b/src/lib/features/category/model/category_model.dart new file mode 100644 index 0000000..7bcef4f --- /dev/null +++ b/src/lib/features/category/model/category_model.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; + +class CategoryModel { + final int id; + final String name; + final String colorCode; + final String profileId; + + const CategoryModel({ + required this.id, + required this.name, + required this.colorCode, + required this.profileId, + }); + + Color get color => _parseHexColor(colorCode); + + factory CategoryModel.fromJson(Map json) { + return CategoryModel( + id: (json['id'] as num?)?.toInt() ?? 0, + name: json['name']?.toString() ?? '', + colorCode: json['color_code']?.toString() ?? '#5A8DF3', + profileId: json['profile_id']?.toString() ?? '', + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'color_code': colorCode, + 'profile_id': profileId, + }; + } + + static Color _parseHexColor(String value) { + var hex = value.trim().replaceFirst('#', ''); + if (hex.length == 6) { + hex = 'FF$hex'; + } + if (hex.length != 8) { + return const Color(0xFF5A8DF3); + } + + final parsed = int.tryParse(hex, radix: 16); + if (parsed == null) { + return const Color(0xFF5A8DF3); + } + return Color(parsed); + } +} + diff --git a/src/lib/features/category/repository/category_repository.dart b/src/lib/features/category/repository/category_repository.dart new file mode 100644 index 0000000..cbfeb93 --- /dev/null +++ b/src/lib/features/category/repository/category_repository.dart @@ -0,0 +1,26 @@ +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../model/category_model.dart'; + +class CategoryRepository { + final SupabaseClient _client; + + CategoryRepository({SupabaseClient? client}) + : _client = client ?? Supabase.instance.client; + + Future> fetchCategories() async { + final user = _client.auth.currentUser; + if (user == null) return []; + + final rows = await _client + .from('category') + .select('id, name, color_code, profile_id') + .eq('profile_id', user.id) + .order('name'); + + return (rows as List) + .map((e) => CategoryModel.fromJson(Map.from(e))) + .toList(); + } +} + diff --git a/src/lib/features/category/view/widgets/category_choice_chips.dart b/src/lib/features/category/view/widgets/category_choice_chips.dart new file mode 100644 index 0000000..e9ecf26 --- /dev/null +++ b/src/lib/features/category/view/widgets/category_choice_chips.dart @@ -0,0 +1,58 @@ +import 'package:flutter/material.dart'; +import 'package:task_management_app/core/utils/adaptive_color_extension.dart'; + +import '../../model/category_model.dart'; + +class CategoryChoiceChips extends StatelessWidget { + const CategoryChoiceChips({ + super.key, + required this.categories, + required this.selectedCategoryId, + required this.onSelected, + }); + + final List categories; + final int? selectedCategoryId; + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + return SizedBox( + height: 40, + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: categories.length, + itemBuilder: (context, index) { + final category = categories[index]; + final adaptiveColor = category.color.toAdaptiveColor(context); + final isSelected = category.id == selectedCategoryId; + return Padding( + padding: const EdgeInsets.only(right: 10), + child: ChoiceChip( + label: Text(category.name), + selected: isSelected, + onSelected: (selected) { + if (selected) onSelected(category); + }, + backgroundColor: adaptiveColor.withValues(alpha: 0.15), + selectedColor: adaptiveColor, + labelStyle: TextStyle( + color: isSelected ? Colors.white : adaptiveColor, + fontSize: 14, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + side: BorderSide( + color: adaptiveColor.withValues(alpha: 0.4), + width: 1, + ), + ), + showCheckmark: false, + ), + ); + }, + ), + ); + } +} + diff --git a/src/lib/features/category/viewmodel/category_viewmodel.dart b/src/lib/features/category/viewmodel/category_viewmodel.dart new file mode 100644 index 0000000..c9e1dc0 --- /dev/null +++ b/src/lib/features/category/viewmodel/category_viewmodel.dart @@ -0,0 +1,41 @@ +import 'package:flutter/foundation.dart'; + +import '../model/category_model.dart'; +import '../repository/category_repository.dart'; + +class CategoryViewModel extends ChangeNotifier { + final CategoryRepository _repository; + + CategoryViewModel({CategoryRepository? repository}) + : _repository = repository ?? CategoryRepository(); + + final List _categories = []; + + List get categories => List.unmodifiable(_categories); + + bool _isLoading = false; + bool get isLoading => _isLoading; + + String? _error; + String? get error => _error; + + Future loadCategories() async { + _isLoading = true; + _error = null; + notifyListeners(); + + try { + final data = await _repository.fetchCategories(); + _categories + ..clear() + ..addAll(data); + } catch (e) { + _error = e.toString(); + _categories.clear(); + } finally { + _isLoading = false; + notifyListeners(); + } + } +} + diff --git a/src/lib/features/main/view/screens/main_screen.dart b/src/lib/features/main/view/screens/main_screen.dart index 0ddd37b..50c09e3 100644 --- a/src/lib/features/main/view/screens/main_screen.dart +++ b/src/lib/features/main/view/screens/main_screen.dart @@ -1,16 +1,18 @@ import 'package:flutter/material.dart'; +// import '../../../tasks/view/screens/home_screen.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/features/chatbot/view/chatbot_view.dart'; import 'package:task_management_app/features/statistics/viewmodel/statistics_viewmodel.dart'; import 'package:task_management_app/features/tasks/view/screens/home_screen.dart'; -import 'package:task_management_app/features/chatbot/view/chatbot_view.dart'; -import 'settings_screen.dart'; import 'package:task_management_app/features/user/viewmodel/user_profile_viewmodel.dart'; + +import '../../../category/viewmodel/category_viewmodel.dart'; import '../../../note/view/focus_screen.dart'; import '../../../note/viewmodel/focus_viewmodel.dart'; import '../../../statistics/view/screens/statistics_screen.dart'; -// import '../../../tasks/view/screens/home_screen.dart'; -import 'package:provider/provider.dart'; - +import '../../../tag/viewmodel/tag_viewmodel.dart'; import '../../../user/view/user_profile_view.dart'; +import 'settings_screen.dart'; class MainScreen extends StatefulWidget { const MainScreen({super.key}); @@ -30,34 +32,50 @@ class _MainScreenState extends State { child: const FocusScreen(), ), ChangeNotifierProvider( - create: (_) => StatisticsViewmodel(), - child: const StatisticsScreen(), + create: (_) => StatisticsViewmodel(), + child: const StatisticsScreen(), ), ChangeNotifierProvider( - create: (_) => UserProfileViewModel(useMockData: true)..loadProfile(), - child: const UserProfileView(), + create: (_) => UserProfileViewModel(useMockData: true)..loadProfile(), + child: const UserProfileView(), ), const SettingsScreen(), ]; + @override + void initState() { + super.initState(); + + WidgetsBinding.instance.addPostFrameCallback((_) { + context.read().loadCategories(); + context.read().loadTags(); + }); + } + @override Widget build(BuildContext context) { final isDark = Theme.of(context).brightness == Brightness.dark; return Scaffold( extendBody: true, - body: IndexedStack( - index: _currentIndex, - children: _screens, - ), + body: IndexedStack(index: _currentIndex, children: _screens), bottomNavigationBar: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 15), decoration: BoxDecoration( color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, - borderRadius: const BorderRadius.only(topLeft: Radius.circular(30), topRight: Radius.circular(30)), - boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 20, offset: const Offset(0, -5))], + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(30), + topRight: Radius.circular(30), + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 20, + offset: const Offset(0, -5), + ), + ], ), child: SafeArea( child: Row( @@ -75,7 +93,12 @@ class _MainScreenState extends State { ); } - Widget _buildNavItem(BuildContext context, IconData icon, String label, int index) { + Widget _buildNavItem( + BuildContext context, + IconData icon, + String label, + int index, + ) { bool isSelected = _currentIndex == index; return GestureDetector( @@ -83,12 +106,15 @@ class _MainScreenState extends State { child: AnimatedContainer( duration: const Duration(milliseconds: 300), curve: Curves.easeInOut, - padding: EdgeInsets.symmetric(horizontal: isSelected ? 15 : 10, vertical: 10), + padding: EdgeInsets.symmetric( + horizontal: isSelected ? 15 : 10, + vertical: 10, + ), decoration: BoxDecoration( color: isSelected ? (Theme.of(context).brightness == Brightness.dark - ? const Color(0xFF23395D) - : const Color(0xFFE8F0FE)) + ? const Color(0xFF23395D) + : const Color(0xFFE8F0FE)) : Colors.transparent, borderRadius: BorderRadius.circular(15), ), @@ -112,10 +138,10 @@ class _MainScreenState extends State { ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.onSurfaceVariant, ), - ) + ), ], ), ), ); } -} \ No newline at end of file +} diff --git a/src/lib/features/statistics/view/screens/statistics_screen.dart b/src/lib/features/statistics/view/screens/statistics_screen.dart index fd18a14..f7bd920 100644 --- a/src/lib/features/statistics/view/screens/statistics_screen.dart +++ b/src/lib/features/statistics/view/screens/statistics_screen.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:provider/provider.dart'; import '../../viewmodel/statistics_viewmodel.dart'; @@ -23,6 +24,10 @@ class _StatisticsScreenState extends State { final userId = Supabase.instance.client.auth.currentUser?.id; if (userId != null) { context.read().getStatisticsData(userId); + final categoryViewModel = context.read(); + if (categoryViewModel.categories.isEmpty) { + categoryViewModel.loadCategories(); + } } }); } diff --git a/src/lib/features/statistics/view/widgets/statistics_widgets.dart b/src/lib/features/statistics/view/widgets/statistics_widgets.dart index c0b6568..e1e3598 100644 --- a/src/lib/features/statistics/view/widgets/statistics_widgets.dart +++ b/src/lib/features/statistics/view/widgets/statistics_widgets.dart @@ -1,5 +1,9 @@ import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/features/category/model/category_model.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; import 'package:task_management_app/features/statistics/model/StatisticsModel.dart'; + import '../../../tasks/model/task_model.dart'; import '../../../tasks/view/screens/task_detail_screen.dart'; @@ -7,7 +11,13 @@ class DailyProgressCard extends StatelessWidget { final int total; final int completed; final double percentage; - const DailyProgressCard({super.key, required this.total, required this.completed, required this.percentage}); + + const DailyProgressCard({ + super.key, + required this.total, + required this.completed, + required this.percentage, + }); @override Widget build(BuildContext context) { @@ -17,7 +27,9 @@ class DailyProgressCard extends StatelessWidget { width: double.infinity, padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 20), decoration: BoxDecoration( - color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + color: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), border: isDark ? Border.all(color: const Color(0xFF2A3E62), width: 1) @@ -43,8 +55,9 @@ class DailyProgressCard extends StatelessWidget { CircularProgressIndicator( value: (total > 0) ? percentage / 100 : 0, strokeWidth: 12, - backgroundColor: - Theme.of(context).colorScheme.surfaceContainerHighest, + backgroundColor: Theme.of( + context, + ).colorScheme.surfaceContainerHighest, valueColor: AlwaysStoppedAnimation( Theme.of(context).colorScheme.primary, ), @@ -99,7 +112,6 @@ class DailyProgressCard extends StatelessWidget { } } - class WeeklyChartCard extends StatelessWidget { final int selectedIndex; final int thisWeekTotal; @@ -121,17 +133,22 @@ class WeeklyChartCard extends StatelessWidget { final isDark = Theme.of(context).brightness == Brightness.dark; final bool isPositive = growthPercentage >= 0; - final Color trendColor = isPositive ? const Color(0xFF3DDC84) : Colors.redAccent; + final Color trendColor = isPositive + ? const Color(0xFF3DDC84) + : Colors.redAccent; final Color trendBgColor = isPositive ? (isDark ? const Color(0xFF173B3D) : const Color(0xFFE9F7EF)) : (isDark ? const Color(0xFF402129) : const Color(0xFFFFEBEE)); - final String trendText = "${isPositive ? '+' : ''}$growthPercentage% vs tuần trước"; + final String trendText = + "${isPositive ? '+' : ''}$growthPercentage% vs tuần trước"; return Container( width: double.infinity, padding: const EdgeInsets.all(25), decoration: BoxDecoration( - color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + color: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), border: isDark ? Border.all(color: const Color(0xFF2A3E62), width: 1) @@ -167,9 +184,22 @@ class WeeklyChartCard extends StatelessWidget { ], ), Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), - decoration: BoxDecoration(color: trendBgColor, borderRadius: BorderRadius.circular(15)), - child: Text(trendText, style: TextStyle(color: trendColor, fontSize: 12, fontWeight: FontWeight.bold)), + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 6, + ), + decoration: BoxDecoration( + color: trendBgColor, + borderRadius: BorderRadius.circular(15), + ), + child: Text( + trendText, + style: TextStyle( + color: trendColor, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), ), ], ), @@ -178,14 +208,48 @@ class WeeklyChartCard extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ - - _buildBar(context, 'T2', weeklyHeights.length > 0 ? weeklyHeights[0] : 0.1, 0), - _buildBar(context, 'T3', weeklyHeights.length > 1 ? weeklyHeights[1] : 0.1, 1), - _buildBar(context, 'T4', weeklyHeights.length > 2 ? weeklyHeights[2] : 0.1, 2), - _buildBar(context, 'T5', weeklyHeights.length > 3 ? weeklyHeights[3] : 0.1, 3), - _buildBar(context, 'T6', weeklyHeights.length > 4 ? weeklyHeights[4] : 0.1, 4), - _buildBar(context, 'T7', weeklyHeights.length > 5 ? weeklyHeights[5] : 0.1, 5), - _buildBar(context, 'CN', weeklyHeights.length > 6 ? weeklyHeights[6] : 0.1, 6), + _buildBar( + context, + 'T2', + weeklyHeights.length > 0 ? weeklyHeights[0] : 0.1, + 0, + ), + _buildBar( + context, + 'T3', + weeklyHeights.length > 1 ? weeklyHeights[1] : 0.1, + 1, + ), + _buildBar( + context, + 'T4', + weeklyHeights.length > 2 ? weeklyHeights[2] : 0.1, + 2, + ), + _buildBar( + context, + 'T5', + weeklyHeights.length > 3 ? weeklyHeights[3] : 0.1, + 3, + ), + _buildBar( + context, + 'T6', + weeklyHeights.length > 4 ? weeklyHeights[4] : 0.1, + 4, + ), + _buildBar( + context, + 'T7', + weeklyHeights.length > 5 ? weeklyHeights[5] : 0.1, + 5, + ), + _buildBar( + context, + 'CN', + weeklyHeights.length > 6 ? weeklyHeights[6] : 0.1, + 6, + ), ], ), ], @@ -193,7 +257,12 @@ class WeeklyChartCard extends StatelessWidget { ); } - Widget _buildBar(BuildContext context, String label, double heightRatio, int index) { + Widget _buildBar( + BuildContext context, + String label, + double heightRatio, + int index, + ) { bool isActive = index == selectedIndex; return GestureDetector( onTap: () => onDaySelected(index), @@ -203,13 +272,13 @@ class WeeklyChartCard extends StatelessWidget { AnimatedContainer( duration: const Duration(milliseconds: 300), width: 35, - height: 100 * (heightRatio > 0 ? heightRatio : 0.1), // Tối thiểu 10% để cột không bị "biến mất" + height: 100 * (heightRatio > 0 ? heightRatio : 0.1), decoration: BoxDecoration( color: isActive ? Theme.of(context).colorScheme.primary : (Theme.of(context).brightness == Brightness.dark - ? const Color(0xFF334764) - : const Color(0xFFF5F7FA)), + ? const Color(0xFF334764) + : const Color(0xFFF5F7FA)), borderRadius: BorderRadius.circular(8), ), ), @@ -239,10 +308,22 @@ class CompletedTaskCard extends StatelessWidget { @override Widget build(BuildContext context) { + final categoryViewModel = context.watch(); final isDark = Theme.of(context).brightness == Brightness.dark; + final CategoryModel fallbackCategory = CategoryModel( + id: 0, + name: 'General', + colorCode: '#5A8DF3', + profileId: '', + ); + final CategoryModel category = categoryViewModel.categories.isNotEmpty + ? categoryViewModel.categories.first + : fallbackCategory; final time = task.updatedAt; - final hour = time.hour > 12 ? time.hour - 12 : (time.hour == 0 ? 12 : time.hour); + final hour = time.hour > 12 + ? time.hour - 12 + : (time.hour == 0 ? 12 : time.hour); final minute = time.minute.toString().padLeft(2, '0'); final period = time.hour >= 12 ? 'PM' : 'AM'; final timeString = 'Hoàn thành lúc $hour:$minute $period'; @@ -255,28 +336,41 @@ class CompletedTaskCard extends StatelessWidget { borderRadius: BorderRadius.circular(25), onTap: () { final mappedTask = TaskModel( - id: task.id.toString(), // Convert int to String if your TaskModel uses String IDs + id: task.id.toString(), + // Convert int to String if your TaskModel uses String IDs title: task.title, - description: 'Completed task details from Statistics.', // Default filler - category: 'Development', // Default filler - startTime: TimeOfDay(hour: task.updatedAt.hour, minute: task.updatedAt.minute), - endTime: TimeOfDay(hour: task.updatedAt.hour + 1, minute: task.updatedAt.minute), // Add 1 hour just for display + description: 'Completed task details from Statistics.', + category: category, + startTime: TimeOfDay( + hour: task.updatedAt.hour, + minute: task.updatedAt.minute, + ), + endTime: TimeOfDay( + hour: task.updatedAt.hour + 1, + minute: task.updatedAt.minute, + ), + // Add 1 hour just for display date: task.updatedAt, ); - Navigator.push(context, PageRouteBuilder( - transitionDuration: const Duration(milliseconds: 500), - pageBuilder: (_, __, ___) => TaskDetailScreen(task: mappedTask), - transitionsBuilder: (_, animation, __, child) { - return FadeTransition(opacity: animation, child: child); - }, - )); + Navigator.push( + context, + PageRouteBuilder( + transitionDuration: const Duration(milliseconds: 500), + pageBuilder: (_, __, ___) => TaskDetailScreen(task: mappedTask), + transitionsBuilder: (_, animation, __, child) { + return FadeTransition(opacity: animation, child: child); + }, + ), + ); }, child: Container( margin: const EdgeInsets.only(bottom: 15), padding: const EdgeInsets.all(20), decoration: BoxDecoration( - color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + color: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(25), border: isDark ? Border.all(color: const Color(0xFF2A3E62), width: 1) @@ -318,7 +412,11 @@ class CompletedTaskCard extends StatelessWidget { ], ), ), - const Icon(Icons.check_circle, color: Color(0xFF2ECC71), size: 28), + const Icon( + Icons.check_circle, + color: Color(0xFF2ECC71), + size: 28, + ), ], ), ), @@ -326,4 +424,4 @@ class CompletedTaskCard extends StatelessWidget { ), ); } -} \ No newline at end of file +} diff --git a/src/lib/features/tag/model/tag_model.dart b/src/lib/features/tag/model/tag_model.dart new file mode 100644 index 0000000..5f5fdb8 --- /dev/null +++ b/src/lib/features/tag/model/tag_model.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; + +class TagModel { + final int id; + final String name; + final String colorCode; + final String profileId; + + const TagModel({ + required this.id, + required this.name, + required this.colorCode, + required this.profileId, + }); + + Color get color => _parseHexColor(colorCode); + + factory TagModel.fromJson(Map json) { + return TagModel( + id: (json['id'] as num?)?.toInt() ?? 0, + name: json['name']?.toString() ?? '', + colorCode: json['color_code']?.toString() ?? '#4A90E2', + profileId: json['profile_id']?.toString() ?? '', + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'color_code': colorCode, + 'profile_id': profileId, + }; + } + + static Color _parseHexColor(String value) { + var hex = value.trim().replaceFirst('#', ''); + if (hex.length == 6) { + hex = 'FF$hex'; + } + if (hex.length != 8) { + return const Color(0xFF4A90E2); + } + + final parsed = int.tryParse(hex, radix: 16); + if (parsed == null) { + return const Color(0xFF4A90E2); + } + return Color(parsed); + } +} + diff --git a/src/lib/features/tag/repository/tag_repository.dart b/src/lib/features/tag/repository/tag_repository.dart new file mode 100644 index 0000000..d2c9158 --- /dev/null +++ b/src/lib/features/tag/repository/tag_repository.dart @@ -0,0 +1,45 @@ +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../model/tag_model.dart'; + +class TagRepository { + final SupabaseClient _client; + + TagRepository({SupabaseClient? client}) + : _client = client ?? Supabase.instance.client; + + Future> fetchTags() async { + final user = _client.auth.currentUser; + if (user == null) return []; + + final rows = await _client + .from('tag') + .select('id, name, color_code, profile_id') + .eq('profile_id', user.id) + .order('name'); + + return (rows as List) + .map((e) => TagModel.fromJson(Map.from(e))) + .toList(); + } + + Future createCustomTag(String name, String colorCode) async { + final user = _client.auth.currentUser; + if (user == null) { + throw Exception('User is not authenticated'); + } + + final inserted = await _client + .from('tag') + .insert({ + 'name': name, + 'color_code': colorCode, + 'profile_id': user.id, + }) + .select('id, name, color_code, profile_id') + .single(); + + return TagModel.fromJson(Map.from(inserted)); + } +} + diff --git a/src/lib/features/tag/view/widgets/tag_selector.dart b/src/lib/features/tag/view/widgets/tag_selector.dart new file mode 100644 index 0000000..50753a6 --- /dev/null +++ b/src/lib/features/tag/view/widgets/tag_selector.dart @@ -0,0 +1,194 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/core/utils/adaptive_color_extension.dart'; +import 'package:task_management_app/features/tag/model/tag_model.dart'; + +import '../../viewmodel/tag_viewmodel.dart'; + +class TagSelector extends StatefulWidget { + const TagSelector({super.key}); + + @override + State createState() => _TagSelectorState(); +} + +class _TagSelectorState extends State { + final TextEditingController _customController = TextEditingController(); + + @override + void dispose() { + _customController.dispose(); + super.dispose(); + } + + void _showAddCustomDialog(BuildContext context, TagViewModel viewModel) { + _customController.clear(); + showDialog( + context: context, + builder: (_) => AlertDialog( + title: const Text('Tạo tag mới'), + content: TextField( + controller: _customController, + maxLength: 12, + decoration: const InputDecoration( + hintText: 'Tên tag (tối đa 12 ký tự)', + border: OutlineInputBorder(), + ), + autofocus: true, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Huỷ'), + ), + ElevatedButton( + onPressed: () async { + final error = await viewModel.addCustomTag(_customController.text); + if (!context.mounted) return; + + if (error != null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(error), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); + } else { + Navigator.pop(context); + } + }, + child: const Text('Thêm'), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + final viewModel = context.watch(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Tags', style: Theme.of(context).textTheme.labelLarge), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Custom', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + GestureDetector( + onTap: viewModel.isLoading + ? null + : () => _showAddCustomDialog(context, viewModel), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(20), + border: Border.all(color: Theme.of(context).colorScheme.outline), + ), + child: Row( + children: [ + Icon( + Icons.add, + size: 14, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 3), + Text( + 'Tạo tag', + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.primary, + ), + ), + ], + ), + ), + ), + ], + ), + const SizedBox(height: 8), + if (viewModel.tags.isEmpty) + Text( + 'Chưa có tag. Nhấn "Tạo tag" để thêm.', + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ) + else + Wrap( + spacing: 8, + runSpacing: 8, + children: viewModel.tags + .map( + (tag) => _TagChip( + tag: tag, + isSelected: viewModel.isTagSelected(tag), + onTap: () => viewModel.toggleTag(tag), + ), + ) + .toList(), + ), + ], + ); + } +} + +class _TagChip extends StatelessWidget { + const _TagChip({ + required this.tag, + required this.isSelected, + required this.onTap, + }); + + final TagModel tag; + final bool isSelected; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final adaptiveTagColor = tag.color.toAdaptiveColor(context); + + return GestureDetector( + onTap: onTap, + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + decoration: BoxDecoration( + color: isSelected + ? adaptiveTagColor + : adaptiveTagColor.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isSelected) ...[ + const Icon(Icons.check, color: Colors.white, size: 14), + const SizedBox(width: 4), + ], + Text( + tag.name, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w500, + color: isSelected ? Colors.white : adaptiveTagColor, + ), + ), + ], + ), + ), + ); + } +} + diff --git a/src/lib/features/tag/viewmodel/tag_viewmodel.dart b/src/lib/features/tag/viewmodel/tag_viewmodel.dart new file mode 100644 index 0000000..d361c77 --- /dev/null +++ b/src/lib/features/tag/viewmodel/tag_viewmodel.dart @@ -0,0 +1,113 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../model/tag_model.dart'; +import '../repository/tag_repository.dart'; + +class TagViewModel extends ChangeNotifier { + static const int _maxCustomTagLength = 12; + + final TagRepository _repository; + + TagViewModel({TagRepository? repository}) + : _repository = repository ?? TagRepository(); + + final List _tags = []; + final Set _selectedTagIds = {}; + + List get tags => List.unmodifiable(_tags); + + List get selectedTags => + _tags.where((tag) => _selectedTagIds.contains(tag.id)).toList(); + + bool _isLoading = false; + bool get isLoading => _isLoading; + + String? _error; + String? get error => _error; + + Future loadTags() async { + _isLoading = true; + _error = null; + notifyListeners(); + + try { + final data = await _repository.fetchTags(); + _tags + ..clear() + ..addAll(data); + _selectedTagIds.removeWhere((id) => !_tags.any((tag) => tag.id == id)); + } catch (e) { + _error = e.toString(); + _tags.clear(); + } finally { + _isLoading = false; + notifyListeners(); + } + } + + bool isTagSelected(TagModel tag) => _selectedTagIds.contains(tag.id); + + void toggleTag(TagModel tag) { + if (_selectedTagIds.contains(tag.id)) { + _selectedTagIds.remove(tag.id); + } else { + _selectedTagIds.add(tag.id); + } + notifyListeners(); + } + + void setSelectedTags(List tags) { + _selectedTagIds + ..clear() + ..addAll(tags.map((e) => e.id)); + notifyListeners(); + } + + void resetSelection() { + _selectedTagIds.clear(); + notifyListeners(); + } + + Future addCustomTag(String name) async { + final trimmed = name.trim(); + if (trimmed.isEmpty) return 'Tên tag không được để trống'; + if (trimmed.length > _maxCustomTagLength) { + return 'Tối đa $_maxCustomTagLength ký tự'; + } + if (_tags.any((t) => t.name.toLowerCase() == trimmed.toLowerCase())) { + return 'Tag đã tồn tại'; + } + + _isLoading = true; + _error = null; + notifyListeners(); + + try { + final colorCode = _generateColorCode(); + final created = await _repository.createCustomTag(trimmed, colorCode); + _tags.add(created); + _selectedTagIds.add(created.id); + return null; + } catch (e) { + _error = e.toString(); + return 'Không thể tạo tag. Vui lòng thử lại'; + } finally { + _isLoading = false; + notifyListeners(); + } + } + + String _generateColorCode() { + const palette = [ + '#E91E63', + '#673AB7', + '#795548', + '#009688', + '#FF5722', + '#4A90E2', + ]; + return palette[_tags.length % palette.length]; + } +} + diff --git a/src/lib/features/tasks/model/task_model.dart b/src/lib/features/tasks/model/task_model.dart index a6a64fb..3fa2db1 100644 --- a/src/lib/features/tasks/model/task_model.dart +++ b/src/lib/features/tasks/model/task_model.dart @@ -1,5 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:task_management_app/features/category/model/category_model.dart'; +import 'package:task_management_app/features/tag/model/tag_model.dart'; + // ─── Priority Enum ─────────────────────────────────────────── enum Priority { low, medium, high, urgent } @@ -44,21 +47,12 @@ extension PriorityExtension on Priority { } } -// ─── Tag Model ─────────────────────────────────────────────── -class TagModel { - final String id; - final String name; - final Color color; - - const TagModel({required this.id, required this.name, required this.color}); -} - // ─── Task Model ────────────────────────────────────────────── class TaskModel { final String id; String title; String description; - String category; + CategoryModel category; TimeOfDay startTime; TimeOfDay endTime; DateTime date; diff --git a/src/lib/features/tasks/view/screens/create_task_screen.dart b/src/lib/features/tasks/view/screens/create_task_screen.dart index 311fd00..7e6fc3e 100644 --- a/src/lib/features/tasks/view/screens/create_task_screen.dart +++ b/src/lib/features/tasks/view/screens/create_task_screen.dart @@ -1,13 +1,16 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; +import 'package:task_management_app/features/category/view/widgets/category_choice_chips.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; +import 'package:task_management_app/features/tag/view/widgets/tag_selector.dart'; +import 'package:task_management_app/features/tag/viewmodel/tag_viewmodel.dart'; + import '../../../../core/widgets/custom_input_field.dart'; import '../../model/task_model.dart'; import '../../viewmodel/task_viewmodel.dart'; import '../widgets/task_widgets.dart'; import '../widgets/priority_selector.dart'; -import '../widgets/tag_selector.dart'; class CreateTaskScreen extends StatefulWidget { const CreateTaskScreen({super.key}); @@ -26,12 +29,28 @@ class _CreateTaskScreenState extends State { DateTime _selectedDate = DateTime.now(); TimeOfDay _startTime = const TimeOfDay(hour: 10, minute: 0); TimeOfDay _endTime = const TimeOfDay(hour: 11, minute: 0); - int _selectedCategoryIndex = 0; + int? _selectedCategoryId; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + context.read().loadCategories(); + context.read().loadTags(); + }); + } @override Widget build(BuildContext context) { + final categoryViewModel = context.watch(); + final tagViewModel = context.watch(); String formattedDate = DateFormat('EEEE, d MMMM').format(_selectedDate); - final isDark = Theme.of(context).brightness == Brightness.dark; + final categories = categoryViewModel.categories; + + if (_selectedCategoryId == null && categories.isNotEmpty) { + _selectedCategoryId = categories.first.id; + } return Scaffold( backgroundColor: Theme.of(context).scaffoldBackgroundColor, @@ -105,47 +124,20 @@ class _CreateTaskScreenState extends State { ), const SizedBox(height: 10), SizedBox( - height: 40, - child: ListView.builder( - scrollDirection: Axis.horizontal, - itemCount: 4, - itemBuilder: (context, index) { - List categories = [ - 'Development', - 'Research', - 'Design', - 'Backend', - ]; - bool isSelected = index == _selectedCategoryIndex; - return Padding( - padding: const EdgeInsets.only(right: 10), - child: ChoiceChip( - label: Text(categories[index]), - selected: isSelected, - onSelected: (selected) => setState(() => _selectedCategoryIndex = selected ? index : 0), - backgroundColor: isDark - ? Theme.of(context).colorScheme.surfaceContainerHighest - : const Color(0xFFF1F7FD), - selectedColor: Theme.of(context).colorScheme.primary, - labelStyle: TextStyle( - color: isSelected - ? Colors.white - : Theme.of(context).colorScheme.primary, - fontSize: 14, - ), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - side: BorderSide( - color: isDark - ? Theme.of(context).colorScheme.outline - : const Color(0xFFF1F7FD), - width: 1, - )), - showCheckmark: false, + child: categories.isEmpty + ? Text( + categoryViewModel.isLoading + ? 'Loading categories...' + : 'No categories found', + style: Theme.of(context).textTheme.bodyMedium, + ) + : CategoryChoiceChips( + categories: categories, + selectedCategoryId: _selectedCategoryId, + onSelected: (category) { + setState(() => _selectedCategoryId = category.id); + }, ), - ); - }, - ), ), const SizedBox(height: 20), @@ -270,26 +262,35 @@ class _CreateTaskScreenState extends State { child: ElevatedButton( onPressed: () { final viewModel = context.read(); - final List categories = [ - 'Development', - 'Research', - 'Design', - 'Backend', - ]; + if (categories.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Please create a category first.'), + ), + ); + return; + } + + final selectedCategory = categories.firstWhere( + (category) => category.id == _selectedCategoryId, + orElse: () => categories.first, + ); + final newTask = TaskModel( id: DateTime.now().millisecondsSinceEpoch .toString(), title: _nameController.text, description: _descController.text, - category: categories[_selectedCategoryIndex], + category: selectedCategory, startTime: _startTime, endTime: _endTime, date: _selectedDate, priority: viewModel.selectedPriority, - tags: List.from(viewModel.selectedTags), + tags: List.from(tagViewModel.selectedTags), ); viewModel.addTask(newTask); viewModel.reset(); + context.read().resetSelection(); Navigator.pop(context); }, style: ElevatedButton.styleFrom( diff --git a/src/lib/features/tasks/view/screens/task_detail_screen.dart b/src/lib/features/tasks/view/screens/task_detail_screen.dart index fd2f832..54b628e 100644 --- a/src/lib/features/tasks/view/screens/task_detail_screen.dart +++ b/src/lib/features/tasks/view/screens/task_detail_screen.dart @@ -1,7 +1,13 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; +import 'package:task_management_app/core/utils/adaptive_color_extension.dart'; +import 'package:task_management_app/features/category/model/category_model.dart'; +import 'package:task_management_app/features/category/view/widgets/category_choice_chips.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; +import 'package:task_management_app/features/tag/model/tag_model.dart'; +import 'package:task_management_app/features/tag/viewmodel/tag_viewmodel.dart'; + import '../../../../core/widgets/custom_input_field.dart'; import '../../model/task_model.dart'; import '../../viewmodel/task_viewmodel.dart'; @@ -20,7 +26,7 @@ class _TaskDetailScreenState extends State { late TextEditingController _descController; late TimeOfDay _startTime; late TimeOfDay _endTime; - late String _currentCategory; + late CategoryModel _currentCategory; late List _currentTags; @override @@ -32,6 +38,12 @@ class _TaskDetailScreenState extends State { _endTime = widget.task.endTime; _currentCategory = widget.task.category; _currentTags = List.from(widget.task.tags); + + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + context.read().loadCategories(); + context.read().loadTags(); + }); } @override @@ -74,12 +86,17 @@ class _TaskDetailScreenState extends State { @override Widget build(BuildContext context) { - final viewModel = context.watch(); + final categoryViewModel = context.watch(); + final tagViewModel = context.watch(); String formattedDate = DateFormat('EEEE, d MMMM').format(widget.task.date); final isDark = Theme.of(context).brightness == Brightness.dark; - // Mock categories (Fetch from database later) - List categories = ['Development', 'Research', 'Design', 'Backend']; + final categories = categoryViewModel.categories; + final tags = tagViewModel.tags; + + if (categories.isNotEmpty && !categories.any((c) => c.id == _currentCategory.id)) { + _currentCategory = categories.first; + } return Scaffold( backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest, @@ -143,48 +160,20 @@ class _TaskDetailScreenState extends State { ), const SizedBox(height: 10), SizedBox( - height: 40, - child: ListView.builder( - scrollDirection: Axis.horizontal, - itemCount: categories.length, - itemBuilder: (context, index) { - bool isSelected = - categories[index] == _currentCategory; - return Padding( - padding: const EdgeInsets.only(right: 10), - child: ChoiceChip( - label: Text(categories[index]), - selected: isSelected, - onSelected: (selected) { - if (selected) { - setState( - () => _currentCategory = categories[index], - ); - } + child: categories.isEmpty + ? Text( + categoryViewModel.isLoading + ? 'Loading categories...' + : 'No categories found', + style: Theme.of(context).textTheme.bodyMedium, + ) + : CategoryChoiceChips( + categories: categories, + selectedCategoryId: _currentCategory.id, + onSelected: (category) { + setState(() => _currentCategory = category); }, - backgroundColor: isDark - ? Theme.of(context).colorScheme.surfaceContainerHighest - : const Color(0xFFF1F7FD), - selectedColor: Theme.of(context).colorScheme.primary, - labelStyle: TextStyle( - color: isSelected - ? Colors.white - : Theme.of(context).colorScheme.primary, - fontSize: 14, - ), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - side: BorderSide( - color: isDark - ? Theme.of(context).colorScheme.outline - : const Color(0xFFF1F7FD), - width: 1, - )), - showCheckmark: false, ), - ); - }, - ), ), const SizedBox(height: 25), @@ -201,70 +190,17 @@ class _TaskDetailScreenState extends State { ), const SizedBox(height: 25), - // ─── Time Tags ──────────────────────────── - Text( - 'Thời gian', - style: Theme.of(context).textTheme.labelLarge, - ), - const SizedBox(height: 10), - Wrap( - spacing: 8, - runSpacing: 8, - children: viewModel.timeTags.map((tag) { - final isSelected = _isTagSelected(tag); - return GestureDetector( - onTap: () => _toggleTag(tag), - child: AnimatedContainer( - duration: const Duration(milliseconds: 200), - padding: const EdgeInsets.symmetric( - horizontal: 14, - vertical: 8, - ), - decoration: BoxDecoration( - color: isSelected - ? tag.color - : tag.color.withValues(alpha: 0.1), - borderRadius: BorderRadius.circular(20), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (isSelected) ...[ - const Icon( - Icons.check, - color: Colors.white, - size: 14, - ), - const SizedBox(width: 4), - ], - Text( - tag.name, - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w500, - color: isSelected - ? Colors.white - : tag.color, - ), - ), - ], - ), - ), - ); - }).toList(), - ), - const SizedBox(height: 20), - - // ─── Status Tags ────────────────────────── + // ─── Tags ───────────────────────────────── Text( - 'Trạng thái', + 'Tags', style: Theme.of(context).textTheme.labelLarge, ), const SizedBox(height: 10), Wrap( spacing: 8, runSpacing: 8, - children: viewModel.statusTags.map((tag) { + children: tags.map((tag) { + final adaptiveTagColor = tag.color.toAdaptiveColor(context); final isSelected = _isTagSelected(tag); return GestureDetector( onTap: () => _toggleTag(tag), @@ -276,8 +212,8 @@ class _TaskDetailScreenState extends State { ), decoration: BoxDecoration( color: isSelected - ? tag.color - : tag.color.withValues(alpha: 0.1), + ? adaptiveTagColor + : adaptiveTagColor.withValues(alpha: 0.15), borderRadius: BorderRadius.circular(20), ), child: Row( @@ -298,7 +234,7 @@ class _TaskDetailScreenState extends State { fontWeight: FontWeight.w500, color: isSelected ? Colors.white - : tag.color, + : adaptiveTagColor, ), ), ], diff --git a/src/lib/features/tasks/view/widgets/tag_selector.dart b/src/lib/features/tasks/view/widgets/tag_selector.dart index 71c15b0..eee3cf6 100644 --- a/src/lib/features/tasks/view/widgets/tag_selector.dart +++ b/src/lib/features/tasks/view/widgets/tag_selector.dart @@ -1,237 +1,12 @@ import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; -import '../../model/task_model.dart'; -import '../../viewmodel/task_viewmodel.dart'; +import 'package:task_management_app/features/tag/view/widgets/tag_selector.dart' + as tag_feature; -class TagSelector extends StatefulWidget { +class TagSelector extends StatelessWidget { const TagSelector({super.key}); - @override - State createState() => _TagSelectorState(); -} - -class _TagSelectorState extends State { - final TextEditingController _customController = TextEditingController(); - - @override - void dispose() { - _customController.dispose(); - super.dispose(); - } - - void _showAddCustomDialog(BuildContext context, TaskViewModel viewModel) { - _customController.clear(); - showDialog( - context: context, - builder: (_) => AlertDialog( - title: const Text('Tạo tag mới'), - content: TextField( - controller: _customController, - maxLength: 12, - decoration: const InputDecoration( - hintText: 'Tên tag (tối đa 12 ký tự)', - border: OutlineInputBorder(), - ), - autofocus: true, - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: const Text('Huỷ'), - ), - ElevatedButton( - onPressed: () { - final error = viewModel.addCustomTag(_customController.text); - if (error != null) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(error), backgroundColor: Colors.red), - ); - } else { - Navigator.pop(context); - } - }, - child: const Text('Thêm'), - ), - ], - ), - ); - } - - @override - Widget build(BuildContext context) { - final viewModel = context.watch(); - - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text('Tags', style: Theme.of(context).textTheme.labelLarge), - const SizedBox(height: 12), - - // ─── Nhóm 1: Loại công việc ─────────────────────── - _buildTagGroup( - label: 'Loại công việc', - tags: viewModel.workTypeTags, - viewModel: viewModel, - ), - const SizedBox(height: 12), - - // ─── Nhóm 2: Thời gian ──────────────────────────── - _buildTagGroup( - label: 'Thời gian', - tags: viewModel.timeTags, - viewModel: viewModel, - ), - const SizedBox(height: 12), - - // ─── Nhóm 3: Trạng thái ─────────────────────────── - _buildTagGroup( - label: 'Trạng thái', - tags: viewModel.statusTags, - viewModel: viewModel, - ), - const SizedBox(height: 12), - - // ─── Nhóm 4: Custom ─────────────────────────────── - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Text( - 'Custom', - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w600, - color: Colors.black54, - ), - ), - // Nút thêm tag mới - if (viewModel.customTags.length < 5) - GestureDetector( - onTap: () => _showAddCustomDialog(context, viewModel), - child: Container( - padding: const EdgeInsets.symmetric( - horizontal: 10, - vertical: 4, - ), - decoration: BoxDecoration( - color: const Color(0xFFF1F7FD), - borderRadius: BorderRadius.circular(20), - border: Border.all(color: Colors.blue.shade200), - ), - child: const Row( - children: [ - Icon(Icons.add, size: 14, color: Colors.blue), - SizedBox(width: 3), - Text( - 'Tạo tag', - style: TextStyle(fontSize: 12, color: Colors.blue), - ), - ], - ), - ), - ), - ], - ), - const SizedBox(height: 8), - - // Hiển thị custom tags đã tạo - viewModel.customTags.isEmpty - ? const Text( - 'Chưa có tag custom. Nhấn "Tạo tag" để thêm.', - style: TextStyle(fontSize: 12, color: Colors.black38), - ) - : Wrap( - spacing: 8, - runSpacing: 8, - children: viewModel.customTags - .map( - (tag) => _TagChip( - tag: tag, - isSelected: viewModel.isTagSelected(tag), - onTap: () => viewModel.toggleTag(tag), - ), - ) - .toList(), - ), - ], - ); - } - - Widget _buildTagGroup({ - required String label, - required List tags, - required TaskViewModel viewModel, - }) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - label, - style: const TextStyle( - fontSize: 13, - fontWeight: FontWeight.w600, - color: Colors.black54, - ), - ), - const SizedBox(height: 6), - Wrap( - spacing: 8, - runSpacing: 8, - children: tags - .map( - (tag) => _TagChip( - tag: tag, - isSelected: viewModel.isTagSelected(tag), - onTap: () => viewModel.toggleTag(tag), - ), - ) - .toList(), - ), - ], - ); - } -} - -// ─── Tag Chip Widget ───────────────────────────────────────── -class _TagChip extends StatelessWidget { - final TagModel tag; - final bool isSelected; - final VoidCallback onTap; - - const _TagChip({ - required this.tag, - required this.isSelected, - required this.onTap, - }); - @override Widget build(BuildContext context) { - return GestureDetector( - onTap: onTap, - child: AnimatedContainer( - duration: const Duration(milliseconds: 200), - padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), - decoration: BoxDecoration( - color: isSelected ? tag.color : tag.color.withValues(alpha: 0.1), - borderRadius: BorderRadius.circular(20), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (isSelected) ...[ - const Icon(Icons.check, color: Colors.white, size: 14), - const SizedBox(width: 4), - ], - Text( - tag.name, - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w500, - color: isSelected ? Colors.white : tag.color, - ), - ), - ], - ), - ), - ); + return const tag_feature.TagSelector(); } } diff --git a/src/lib/features/tasks/viewmodel/task_viewmodel.dart b/src/lib/features/tasks/viewmodel/task_viewmodel.dart index 347d2bc..c943500 100644 --- a/src/lib/features/tasks/viewmodel/task_viewmodel.dart +++ b/src/lib/features/tasks/viewmodel/task_viewmodel.dart @@ -1,143 +1,21 @@ -import 'dart:convert'; import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; +import 'package:task_management_app/features/tag/model/tag_model.dart'; + import '../model/task_model.dart'; class TaskViewModel extends ChangeNotifier { - final List workTypeTags = [ - TagModel(id: 'work', name: 'Work', color: const Color(0xFF2196F3)), - TagModel(id: 'study', name: 'Study', color: const Color(0xFF9C27B0)), - TagModel(id: 'personal', name: 'Personal', color: const Color(0xFF4CAF50)), - TagModel(id: 'project', name: 'Project', color: const Color(0xFFFF9800)), - ]; - - final List timeTags = [ - TagModel(id: 'today', name: 'Today', color: const Color(0xFF00BCD4)), - TagModel(id: 'tomorrow', name: 'Tomorrow', color: const Color(0xFF3F51B5)), - TagModel( - id: 'this_week', - name: 'This Week', - color: const Color(0xFF009688), - ), - TagModel(id: 'later', name: 'Later', color: const Color(0xFF607D8B)), - ]; - - final List statusTags = [ - TagModel(id: 'pending', name: 'Pending', color: const Color(0xFFFF9800)), - TagModel( - id: 'in_progress', - name: 'In Progress', - color: const Color(0xFF2196F3), - ), - TagModel( - id: 'completed', - name: 'Completed', - color: const Color(0xFF4CAF50), - ), - TagModel( - id: 'cancelled', - name: 'Cancelled', - color: const Color(0xFF9E9E9E), - ), - ]; - - // ─── Custom Tags (lưu SharedPreferences) ──────────────── - List _customTags = []; - List get customTags => List.unmodifiable(_customTags); - - static const _customTagsKey = 'custom_tags'; - static const _maxCustomTags = 5; - static const _maxCustomTagLength = 12; - - TaskViewModel() { - _loadCustomTags(); - } - - Future _loadCustomTags() async { - final prefs = await SharedPreferences.getInstance(); - final raw = prefs.getString(_customTagsKey); - if (raw != null) { - final List decoded = jsonDecode(raw); - _customTags = decoded - .map( - (e) => TagModel( - id: e['id'], - name: e['name'], - color: Color(e['color']), - ), - ) - .toList(); - notifyListeners(); - } - } - - Future _saveCustomTags() async { - final prefs = await SharedPreferences.getInstance(); - final encoded = jsonEncode( - _customTags - .map((t) => {'id': t.id, 'name': t.name, 'color': t.color.toARGB32()}) - .toList(), - ); - await prefs.setString(_customTagsKey, encoded); - } - - // Trả về lỗi nếu có, null nếu thành công - String? addCustomTag(String name) { - name = name.trim(); - if (name.isEmpty) return 'Tên tag không được để trống'; - if (name.length > _maxCustomTagLength) - return 'Tối đa $_maxCustomTagLength ký tự'; - if (_customTags.length >= _maxCustomTags) - return 'Tối đa $_maxCustomTags tag custom'; - if (_customTags.any((t) => t.name.toLowerCase() == name.toLowerCase())) { - return 'Tag đã tồn tại'; - } - _customTags.add( - TagModel( - id: 'custom_${DateTime.now().millisecondsSinceEpoch}', - name: name, - color: _customTagColors[_customTags.length % _customTagColors.length], - ), - ); - _saveCustomTags(); - notifyListeners(); - return null; - } - - final List _customTagColors = const [ - Color(0xFFE91E63), - Color(0xFF673AB7), - Color(0xFF795548), - Color(0xFF009688), - Color(0xFFFF5722), - ]; - // ─── State tạo task ───────────────────────────────────── Priority _selectedPriority = Priority.medium; - final List _selectedTags = []; Priority get selectedPriority => _selectedPriority; - List get selectedTags => List.unmodifiable(_selectedTags); void setPriority(Priority priority) { _selectedPriority = priority; notifyListeners(); } - void toggleTag(TagModel tag) { - if (_selectedTags.any((t) => t.id == tag.id)) { - _selectedTags.removeWhere((t) => t.id == tag.id); - } else { - _selectedTags.add(tag); - } - notifyListeners(); - } - - bool isTagSelected(TagModel tag) => _selectedTags.any((t) => t.id == tag.id); - void reset() { _selectedPriority = Priority.medium; - _selectedTags.clear(); notifyListeners(); } @@ -189,7 +67,7 @@ class TaskViewModel extends ChangeNotifier { } if (_filterTagId != null) { result = result - .where((t) => t.tags.any((tag) => tag.id == _filterTagId)) + .where((t) => t.tags.any((tag) => tag.id.toString() == _filterTagId)) .toList(); } diff --git a/src/lib/main.dart b/src/lib/main.dart index 6803683..3be01b7 100644 --- a/src/lib/main.dart +++ b/src/lib/main.dart @@ -3,7 +3,9 @@ import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:task_management_app/features/auth/presentation/view/auth_gate.dart'; import 'package:task_management_app/features/auth/presentation/view/login_view.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; import 'package:task_management_app/features/main/view/screens/main_screen.dart'; +import 'package:task_management_app/features/tag/viewmodel/tag_viewmodel.dart'; import 'package:task_management_app/features/tasks/viewmodel/task_viewmodel.dart'; import 'core/theme/app_theme.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -36,6 +38,12 @@ Future main() async { ChangeNotifierProvider( create: (_) => TaskViewModel(), ), + ChangeNotifierProvider( + create: (_) => CategoryViewModel(), + ), + ChangeNotifierProvider( + create: (_) => TagViewModel(), + ), ], child: const TaskApp())); } diff --git a/src/pubspec.lock b/src/pubspec.lock index 33dc948..72a5d4a 100644 --- a/src/pubspec.lock +++ b/src/pubspec.lock @@ -53,10 +53,10 @@ packages: dependency: transitive description: name: characters - sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 url: "https://pub.dev" source: hosted - version: "1.4.1" + version: "1.4.0" clock: dependency: transitive description: @@ -436,18 +436,18 @@ packages: dependency: transitive description: name: matcher - sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 url: "https://pub.dev" source: hosted - version: "0.12.19" + version: "0.12.17" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec url: "https://pub.dev" source: hosted - version: "0.13.0" + version: "0.11.1" meta: dependency: transitive description: @@ -745,10 +745,10 @@ packages: dependency: transitive description: name: test_api - sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" + sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 url: "https://pub.dev" source: hosted - version: "0.7.10" + version: "0.7.7" typed_data: dependency: transitive description: