feat: 实现用户画像、占卜历史与后端用户管理模块

This commit is contained in:
ZL-Q
2026-04-06 01:28:10 +08:00
parent d87b2e1e3a
commit 8a18b3528b
77 changed files with 5850 additions and 2604 deletions
@@ -0,0 +1,90 @@
import 'package:dio/dio.dart';
import '../../../../core/network/api_problem.dart';
import '../../../../data/network/api_client.dart';
import '../models/profile_settings.dart';
class ProfileApi {
const ProfileApi({required ApiClient apiClient}) : _apiClient = apiClient;
final ApiClient _apiClient;
Future<ProfileSettingsV1> getProfile() async {
final json = await _apiClient.getJson('/api/v1/users/me/profile');
return _toSettings(json);
}
Future<ProfileSettingsV1> updateProfile(ProfileSettingsV1 next) async {
final payload = <String, dynamic>{
'display_name': next.displayName,
'bio': next.bio,
if (next.avatarPath != null && next.avatarPath!.isNotEmpty)
'avatar_path': next.avatarPath,
};
final json = await _apiClient.rawDio.patch<Map<String, dynamic>>(
'/api/v1/users/me/profile',
data: payload,
);
final data = json.data;
if (data is! Map<String, dynamic>) {
throw ApiProblem(
status: 502,
title: 'Invalid profile payload',
detail: 'Expected profile response object',
);
}
return _toSettings(data);
}
Future<ProfileSettingsV1> uploadAvatar(String filePath) async {
final formData = FormData.fromMap({
'file': await MultipartFile.fromFile(filePath),
});
final response = await _apiClient.rawDio.post<Map<String, dynamic>>(
'/api/v1/users/me/avatar',
data: formData,
);
final data = response.data;
if (data is! Map<String, dynamic>) {
throw ApiProblem(
status: 502,
title: 'Invalid profile payload',
detail: 'Expected profile response object',
);
}
return _toSettings(data);
}
ProfileSettingsV1 _toSettings(Map<String, dynamic> json) {
final settingsRaw = json['settings'];
final preferencesRaw = settingsRaw is Map<String, dynamic>
? settingsRaw['preferences']
: null;
final preferences = preferencesRaw is Map<String, dynamic>
? PreferenceSettings(
interfaceLanguage:
(preferencesRaw['interface_language'] as String?) ?? 'zh-CN',
aiLanguage: (preferencesRaw['ai_language'] as String?) ?? 'zh-CN',
timezone:
(preferencesRaw['timezone'] as String?) ?? 'Asia/Shanghai',
country: (preferencesRaw['country'] as String?) ?? 'CN',
)
: const PreferenceSettings();
return ProfileSettingsV1(
displayName: (json['display_name'] as String?) ?? '',
bio: (json['bio'] as String?) ?? '',
avatarPath: json['avatar_path'] as String?,
avatarUrl: json['avatar_url'] as String?,
preferences: preferences,
privacy: settingsRaw is Map<String, dynamic>
? (settingsRaw['privacy'] as Map<String, dynamic>? ??
const <String, dynamic>{})
: const <String, dynamic>{},
notification: settingsRaw is Map<String, dynamic>
? (settingsRaw['notification'] as Map<String, dynamic>? ??
const <String, dynamic>{})
: const <String, dynamic>{},
);
}
}
@@ -40,24 +40,40 @@ class PreferenceSettings {
class ProfileSettingsV1 {
const ProfileSettingsV1({
this.version = 1,
this.displayName = '',
this.bio = '',
this.avatarPath,
this.avatarUrl,
this.preferences = const PreferenceSettings(),
this.privacy = const <String, Object?>{},
this.notification = const <String, Object?>{},
});
final int version;
final String displayName;
final String bio;
final String? avatarPath;
final String? avatarUrl;
final PreferenceSettings preferences;
final Map<String, Object?> privacy;
final Map<String, Object?> notification;
ProfileSettingsV1 copyWith({
int? version,
String? displayName,
String? bio,
String? avatarPath,
String? avatarUrl,
PreferenceSettings? preferences,
Map<String, Object?>? privacy,
Map<String, Object?>? notification,
}) {
return ProfileSettingsV1(
version: version ?? this.version,
displayName: displayName ?? this.displayName,
bio: bio ?? this.bio,
avatarPath: avatarPath ?? this.avatarPath,
avatarUrl: avatarUrl ?? this.avatarUrl,
preferences: preferences ?? this.preferences,
privacy: privacy ?? this.privacy,
notification: notification ?? this.notification,
@@ -0,0 +1,278 @@
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../../../../core/logging/logger.dart';
import '../../../../l10n/app_localizations.dart';
import '../../../../shared/theme/design_tokens.dart';
import '../../../../shared/widgets/toast/toast.dart';
import '../../../../shared/widgets/toast/toast_type.dart';
import '../../data/models/profile_settings.dart';
class ProfileEditScreen extends StatefulWidget {
const ProfileEditScreen({
super.key,
required this.account,
required this.settings,
required this.onUploadAvatar,
});
final String account;
final ProfileSettingsV1 settings;
final Future<ProfileSettingsV1> Function(String filePath) onUploadAvatar;
@override
State<ProfileEditScreen> createState() => _ProfileEditScreenState();
}
class _ProfileEditScreenState extends State<ProfileEditScreen> {
final Logger _logger = getLogger('features.settings.profile_edit_screen');
final ImagePicker _imagePicker = ImagePicker();
late final TextEditingController _nameController;
late final TextEditingController _bioController;
bool _uploadingAvatar = false;
String? _avatarPath;
String? _avatarPreviewUrl;
@override
void initState() {
super.initState();
_nameController = TextEditingController(
text: widget.settings.displayName.isEmpty
? widget.account
: widget.settings.displayName,
);
_bioController = TextEditingController(text: widget.settings.bio);
_avatarPath = widget.settings.avatarPath;
_avatarPreviewUrl = widget.settings.avatarUrl;
}
@override
void dispose() {
_nameController.dispose();
_bioController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
final l10n = AppLocalizations.of(context)!;
return Scaffold(
backgroundColor: colors.surfaceContainerLow,
appBar: AppBar(
title: Text(l10n.settingsEditProfileTitle),
centerTitle: true,
backgroundColor: colors.surfaceContainerLow,
surfaceTintColor: colors.surfaceContainerLow,
),
body: ListView(
padding: const EdgeInsets.all(AppSpacing.lg),
children: [
Container(
padding: const EdgeInsets.all(AppSpacing.lg),
decoration: BoxDecoration(
color: colors.surface,
borderRadius: BorderRadius.circular(AppRadius.lg),
border: Border.all(color: colors.outlineVariant),
),
child: Column(
children: [
Text(
l10n.settingsAvatar,
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: AppSpacing.lg),
Stack(
alignment: Alignment.bottomRight,
children: [
Container(
width: 112,
height: 112,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: colors.surfaceContainerHighest,
border: Border.all(
color: colors.primary.withValues(alpha: 0.3),
width: 2,
),
),
clipBehavior: Clip.antiAlias,
child:
(_avatarPreviewUrl != null &&
_avatarPreviewUrl!.isNotEmpty)
? Image.network(
_avatarPreviewUrl!,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return Icon(
Icons.person,
size: 44,
color: colors.primary,
);
},
)
: Icon(Icons.person, size: 44, color: colors.primary),
),
FilledButton(
onPressed: _uploadingAvatar ? null : _pickAndUploadAvatar,
style: FilledButton.styleFrom(
minimumSize: const Size(44, 44),
shape: const CircleBorder(),
padding: EdgeInsets.zero,
),
child: _uploadingAvatar
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.photo_camera_outlined, size: 20),
),
],
),
const SizedBox(height: AppSpacing.md),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: _uploadingAvatar ? null : _pickAndUploadAvatar,
icon: const Icon(Icons.photo_library_outlined),
label: Text(
_uploadingAvatar
? l10n.settingsAvatarUploading
: l10n.settingsAvatarChooseFromAlbum,
),
),
),
],
),
),
const SizedBox(height: AppSpacing.xl),
Text(
l10n.settingsDisplayName,
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: AppSpacing.sm),
TextField(
controller: _nameController,
maxLength: 20,
decoration: InputDecoration(
hintText: l10n.settingsDisplayNameHint,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(AppRadius.md),
),
),
),
const SizedBox(height: AppSpacing.lg),
Text(
l10n.settingsBio,
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: AppSpacing.sm),
TextField(
controller: _bioController,
minLines: 3,
maxLines: 5,
maxLength: 80,
decoration: InputDecoration(
hintText: l10n.settingsBioHint,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(AppRadius.md),
),
),
),
const SizedBox(height: AppSpacing.xl),
SizedBox(
width: double.infinity,
child: FilledButton(onPressed: _save, child: Text(l10n.confirm)),
),
],
),
);
}
void _save() {
final l10n = AppLocalizations.of(context)!;
final name = _nameController.text.trim();
if (name.isEmpty) {
Toast.show(
context,
l10n.settingsDisplayNameRequired,
type: ToastType.warning,
);
return;
}
Navigator.of(context).pop(
widget.settings.copyWith(
displayName: name,
bio: _bioController.text.trim(),
avatarPath: _avatarPath,
avatarUrl: _avatarPreviewUrl,
),
);
}
Future<void> _pickAndUploadAvatar() async {
XFile? picked;
try {
picked = await _imagePicker.pickImage(
source: ImageSource.gallery,
maxWidth: 1024,
imageQuality: 85,
requestFullMetadata: false,
);
} catch (error, stackTrace) {
_logger.error(
message: 'Avatar picker failed to open photo library',
error: error,
stackTrace: stackTrace,
);
if (!mounted) {
return;
}
Toast.show(
context,
AppLocalizations.of(context)!.settingsAvatarPickPermissionHint,
type: ToastType.error,
);
return;
}
if (picked == null || !mounted) {
return;
}
setState(() {
_uploadingAvatar = true;
});
try {
final updated = await widget.onUploadAvatar(picked.path);
if (!mounted) {
return;
}
setState(() {
_avatarPath = updated.avatarPath;
_avatarPreviewUrl = updated.avatarUrl;
});
} catch (error, stackTrace) {
_logger.error(
message: 'Avatar upload failed from profile editor',
error: error,
stackTrace: stackTrace,
);
if (!mounted) {
return;
}
Toast.show(
context,
AppLocalizations.of(context)!.errorRequestGeneric,
type: ToastType.error,
);
} finally {
if (mounted) {
setState(() {
_uploadingAvatar = false;
});
}
}
}
}
@@ -1,12 +1,17 @@
import 'package:flutter/material.dart';
import '../../../../l10n/app_localizations.dart';
import '../../../../core/logging/logger.dart';
import '../../../../shared/theme/design_tokens.dart';
import '../../../../shared/widgets/app_modal_dialog.dart';
import '../../../../shared/widgets/toast/toast.dart';
import '../../../../shared/widgets/toast/toast_type.dart';
import '../../data/models/profile_settings.dart';
import '../widgets/settings_section_widgets.dart';
import 'coin_center_screen.dart';
import 'general_settings_screen.dart';
import 'legal_center_screen.dart';
import 'profile_edit_screen.dart';
class SettingsScreen extends StatefulWidget {
const SettingsScreen({
@@ -15,6 +20,8 @@ class SettingsScreen extends StatefulWidget {
required this.settings,
required this.coinBalance,
required this.onInterfaceLanguageChanged,
required this.onSettingsChanged,
required this.onUploadAvatar,
required this.onLogout,
});
@@ -22,6 +29,8 @@ class SettingsScreen extends StatefulWidget {
final ProfileSettingsV1 settings;
final int coinBalance;
final Future<void> Function(String languageTag) onInterfaceLanguageChanged;
final Future<void> Function(ProfileSettingsV1 settings) onSettingsChanged;
final Future<ProfileSettingsV1> Function(String filePath) onUploadAvatar;
final Future<void> Function() onLogout;
@override
@@ -29,6 +38,7 @@ class SettingsScreen extends StatefulWidget {
}
class _SettingsScreenState extends State<SettingsScreen> {
final Logger _logger = getLogger('features.settings.settings_screen');
late ProfileSettingsV1 _settings;
bool _isLoggingOut = false;
@@ -38,6 +48,14 @@ class _SettingsScreenState extends State<SettingsScreen> {
_settings = widget.settings;
}
@override
void didUpdateWidget(covariant SettingsScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.settings != widget.settings) {
_settings = widget.settings;
}
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
@@ -59,7 +77,15 @@ class _SettingsScreenState extends State<SettingsScreen> {
AppSpacing.xl,
),
children: [
ProfileHeaderCard(account: widget.account),
ProfileHeaderCard(
account: widget.account,
displayName: _settings.displayName.isEmpty
? widget.account
: _settings.displayName,
bio: _settings.bio,
avatarUrl: _settings.avatarUrl,
onEditTap: _openProfileEdit,
),
const SizedBox(height: AppSpacing.lg),
WalletHeroCard(
balance: widget.coinBalance,
@@ -67,7 +93,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
onTap: _openCoinCenter,
),
const SizedBox(height: AppSpacing.xl),
SectionLabel(text: l10n.settingsSectionQuickAccess),
SettingsGroupCard(
children: [
SettingsMenuTile(
@@ -131,6 +156,44 @@ class _SettingsScreenState extends State<SettingsScreen> {
});
}
Future<void> _openProfileEdit() async {
final result = await Navigator.of(context).push<ProfileSettingsV1>(
MaterialPageRoute<ProfileSettingsV1>(
builder: (_) => ProfileEditScreen(
account: widget.account,
settings: _settings,
onUploadAvatar: widget.onUploadAvatar,
),
),
);
if (result == null || !mounted) {
return;
}
try {
await widget.onSettingsChanged(result);
if (!mounted) {
return;
}
setState(() {
_settings = result;
});
} catch (error, stackTrace) {
_logger.error(
message: 'Failed to save profile settings',
error: error,
stackTrace: stackTrace,
);
if (!mounted) {
return;
}
Toast.show(
context,
AppLocalizations.of(context)!.errorRequestGeneric,
type: ToastType.error,
);
}
}
Future<void> _openLegalCenter() async {
await Navigator.of(context).push<void>(
MaterialPageRoute<void>(builder: (_) => const LegalCenterScreen()),
@@ -142,21 +205,20 @@ class _SettingsScreenState extends State<SettingsScreen> {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: Text(l10n.settingsLogoutDialogTitle),
content: Text(l10n.settingsLogoutDialogBody),
return AppModalDialog(
title: l10n.settingsLogoutDialogTitle,
message: l10n.settingsLogoutDialogBody,
icon: Icons.logout_rounded,
actions: [
TextButton(
AppModalDialogAction(
label: l10n.settingsCancel,
onPressed: () => Navigator.of(dialogContext).pop(false),
child: Text(l10n.settingsCancel),
),
FilledButton(
AppModalDialogAction(
label: l10n.logout,
primary: true,
destructive: true,
onPressed: () => Navigator.of(dialogContext).pop(true),
style: FilledButton.styleFrom(
backgroundColor: Theme.of(dialogContext).colorScheme.error,
foregroundColor: Theme.of(dialogContext).colorScheme.onError,
),
child: Text(l10n.logout),
),
],
);
@@ -171,6 +233,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
});
try {
await widget.onLogout();
if (!mounted) {
return;
}
Navigator.of(context).popUntil((route) => route.isFirst);
} finally {
if (mounted) {
setState(() {
@@ -120,9 +120,20 @@ class SettingsMenuTile extends StatelessWidget {
}
class ProfileHeaderCard extends StatelessWidget {
const ProfileHeaderCard({super.key, required this.account});
const ProfileHeaderCard({
super.key,
required this.account,
required this.displayName,
required this.bio,
required this.avatarUrl,
required this.onEditTap,
});
final String account;
final String displayName;
final String bio;
final String? avatarUrl;
final VoidCallback onEditTap;
@override
Widget build(BuildContext context) {
@@ -137,22 +148,83 @@ class ProfileHeaderCard extends StatelessWidget {
child: Padding(
padding: const EdgeInsets.all(AppSpacing.lg),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CircleAvatar(
radius: 28,
backgroundColor: colors.surfaceContainerHighest,
child: Icon(Icons.person_rounded, color: colors.primary),
Container(
width: 56,
height: 56,
decoration: BoxDecoration(
color: colors.surfaceContainerHighest,
borderRadius: BorderRadius.circular(AppRadius.full),
),
alignment: Alignment.center,
child: _AvatarContent(avatarUrl: avatarUrl),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(account, style: Theme.of(context).textTheme.titleMedium),
Text(
displayName,
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: AppSpacing.xs),
Text(
account,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: colors.onSurfaceVariant,
),
),
if (bio.isNotEmpty) ...[
const SizedBox(height: AppSpacing.sm),
Text(
bio,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodyMedium,
),
],
],
),
),
Icon(Icons.edit_outlined, color: colors.outline, size: 20),
const SizedBox(width: AppSpacing.sm),
Material(
color: colors.surface,
elevation: 2,
shadowColor: colors.shadow.withValues(alpha: 0.35),
borderRadius: BorderRadius.circular(AppRadius.full),
child: InkWell(
onTap: onEditTap,
borderRadius: BorderRadius.circular(AppRadius.full),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.md,
vertical: AppSpacing.sm,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(AppRadius.full),
border: Border.all(
color: colors.primary.withValues(alpha: 0.24),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.edit_rounded, color: colors.primary, size: 18),
const SizedBox(width: AppSpacing.xs),
Text(
AppLocalizations.of(context)!.settingsEditProfileAction,
style: Theme.of(context).textTheme.labelLarge?.copyWith(
color: colors.primary,
fontWeight: FontWeight.w700,
),
),
],
),
),
),
),
],
),
),
@@ -160,6 +232,32 @@ class ProfileHeaderCard extends StatelessWidget {
}
}
class _AvatarContent extends StatelessWidget {
const _AvatarContent({required this.avatarUrl});
final String? avatarUrl;
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
final url = avatarUrl?.trim() ?? '';
if (url.isNotEmpty) {
return ClipOval(
child: Image.network(
url,
width: 56,
height: 56,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return Icon(Icons.person_rounded, color: colors.primary, size: 30);
},
),
);
}
return Icon(Icons.person_rounded, color: colors.primary, size: 30);
}
}
class WalletHeroCard extends StatelessWidget {
const WalletHeroCard({
super.key,