feat(profile): 实现个人资料编辑与策略本地缓存

- 将资料编辑页重构为可交互表单,支持昵称、签名编辑与头像更换
- 新增 DioClient 本地缓存读取与写入方法,支持离线读取策略快照
- 设备策略切换后自动使本地缓存失效,避免数据不一致
- Home Tab 切换时选中态跟随可见页面,滑动过程中实时更新底栏高亮
- 系统设置页引入 loading 遮罩层,防止切换开关时重复操作
- 个人资料页接入 profileController 展示真实用户信息与加载状态
- 适配深色模式,修正 home_tab 中头像与文字颜色硬编码问题
This commit is contained in:
tongtong committed 2026-11-09 09:24:51 +08:00
1 parent 5f84a64c3e
commit e06e12fbbc
30 files changed
+2059 -336

No files matched your search

@@ -0,0 +1,82 @@
import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../../core/network/dio_client.dart';
import '../../../core/storage/token_storage.dart';
import '../domain/profile_models.dart';
import '../domain/profile_repository.dart';
part 'profile_repository_impl.g.dart';
@riverpod
ProfileRepository profileRepository(ProfileRepositoryRef ref) =>
ProfileRepositoryImpl();
class ProfileRepositoryImpl implements ProfileRepository {
static const _path = 'v1/client/account/profile';
final _picker = ImagePicker();
UserProfile _parse(dynamic data) {
final profile = UserProfile.fromJson(
Map<String, dynamic>.from(data as Map),
);
final avatar = profile.avatar;
if (avatar == null || avatar.isEmpty) return profile;
return profile.copyWith(
avatar: Uri.parse(
DioClient.instance.options.baseUrl,
).resolve(avatar).toString(),
);
}
@override
Future<UserProfile> load() async =>
_parse(await DioClient.get(_path, allowStale: true));
@override
Future<UserProfile> save(String nickname, String signature) async {
final profile = _parse(
await DioClient.put(
_path,
data: {'nickname': nickname, 'signature': signature},
),
);
await DioClient.storeReadCache(_path, profile.toJson());
return profile;
}
@override
Future<UserProfile?> chooseAvatar() async {
final version = TokenStorage.sessionVersion;
final image = await _picker.pickImage(
source: ImageSource.gallery,
maxWidth: 1024,
maxHeight: 1024,
imageQuality: 85,
);
if (image == null || version != TokenStorage.sessionVersion) return null;
if (await image.length() > 5 * 1024 * 1024) {
throw const ProfileInputException(ProfileIssue.avatarTooLarge);
}
final name = image.name.toLowerCase();
final png = name.endsWith('.png');
if (!png && !name.endsWith('.jpg') && !name.endsWith('.jpeg')) {
throw const ProfileInputException(ProfileIssue.avatarUnsupported);
}
final bytes = await image.readAsBytes();
if (version != TokenStorage.sessionVersion) return null;
final data = FormData.fromMap({
'file': MultipartFile.fromBytes(
bytes,
filename: png ? 'avatar.png' : 'avatar.jpg',
contentType: DioMediaType('image', png ? 'png' : 'jpeg'),
),
});
final profile = _parse(
await DioClient.postMultipart('$_path/avatar', formData: data),
);
await DioClient.storeReadCache(_path, profile.toJson());
return profile;
}
}
@@ -0,0 +1,28 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'profile_repository_impl.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
String _$profileRepositoryHash() => r'53edb40b05a538aa85e7ff4d1d82072e4c31e5d0';
/// See also [profileRepository].
@ProviderFor(profileRepository)
final profileRepositoryProvider =
AutoDisposeProvider<ProfileRepository>.internal(
profileRepository,
name: r'profileRepositoryProvider',
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
? null
: _$profileRepositoryHash,
dependencies: null,
allTransitiveDependencies: null,
);
@Deprecated('Will be removed in 3.0. Use Ref instead')
// ignore: unused_element
typedef ProfileRepositoryRef = AutoDisposeProviderRef<ProfileRepository>;
// ignore_for_file: type=lint
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
@@ -0,0 +1,53 @@
// Freezed forwards factory parameter annotations to generated fields.
// ignore_for_file: invalid_annotation_target
import 'package:freezed_annotation/freezed_annotation.dart';
part 'profile_models.freezed.dart';
part 'profile_models.g.dart';
@freezed
class UserProfile with _$UserProfile {
const UserProfile._();
const factory UserProfile({
@JsonKey(fromJson: _idToString) required String id,
@Default('') String username,
@Default('') String nickname,
@Default('') String signature,
String? avatar,
}) = _UserProfile;
factory UserProfile.fromJson(Map<String, dynamic> json) =>
_$UserProfileFromJson(json);
String get displayName => nickname.isNotEmpty ? nickname : username;
}
String _idToString(Object? value) => value?.toString() ?? '';
enum ProfileIssue {
nicknameInvalid,
signatureInvalid,
avatarTooLarge,
avatarUnsupported,
}
class ProfileInputException implements Exception {
const ProfileInputException(this.issue);
final ProfileIssue issue;
}
@freezed
class ProfileState with _$ProfileState {
const factory ProfileState({
UserProfile? profile,
@Default(true) bool loading,
@Default(false) bool saving,
String? alert,
ProfileIssue? issue,
}) = _ProfileState;
factory ProfileState.fromJson(Map<String, dynamic> json) =>
_$ProfileStateFromJson(json);
}
@@ -0,0 +1,535 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'profile_models.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models',
);
UserProfile _$UserProfileFromJson(Map<String, dynamic> json) {
return _UserProfile.fromJson(json);
}
/// @nodoc
mixin _$UserProfile {
@JsonKey(fromJson: _idToString)
String get id => throw _privateConstructorUsedError;
String get username => throw _privateConstructorUsedError;
String get nickname => throw _privateConstructorUsedError;
String get signature => throw _privateConstructorUsedError;
String? get avatar => throw _privateConstructorUsedError;
/// Serializes this UserProfile to a JSON map.
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
/// Create a copy of UserProfile
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
$UserProfileCopyWith<UserProfile> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $UserProfileCopyWith<$Res> {
factory $UserProfileCopyWith(
UserProfile value,
$Res Function(UserProfile) then,
) = _$UserProfileCopyWithImpl<$Res, UserProfile>;
@useResult
$Res call({
@JsonKey(fromJson: _idToString) String id,
String username,
String nickname,
String signature,
String? avatar,
});
}
/// @nodoc
class _$UserProfileCopyWithImpl<$Res, $Val extends UserProfile>
implements $UserProfileCopyWith<$Res> {
_$UserProfileCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
/// Create a copy of UserProfile
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? id = null,
Object? username = null,
Object? nickname = null,
Object? signature = null,
Object? avatar = freezed,
}) {
return _then(
_value.copyWith(
id: null == id
? _value.id
: id // ignore: cast_nullable_to_non_nullable
as String,
username: null == username
? _value.username
: username // ignore: cast_nullable_to_non_nullable
as String,
nickname: null == nickname
? _value.nickname
: nickname // ignore: cast_nullable_to_non_nullable
as String,
signature: null == signature
? _value.signature
: signature // ignore: cast_nullable_to_non_nullable
as String,
avatar: freezed == avatar
? _value.avatar
: avatar // ignore: cast_nullable_to_non_nullable
as String?,
)
as $Val,
);
}
}
/// @nodoc
abstract class _$$UserProfileImplCopyWith<$Res>
implements $UserProfileCopyWith<$Res> {
factory _$$UserProfileImplCopyWith(
_$UserProfileImpl value,
$Res Function(_$UserProfileImpl) then,
) = __$$UserProfileImplCopyWithImpl<$Res>;
@override
@useResult
$Res call({
@JsonKey(fromJson: _idToString) String id,
String username,
String nickname,
String signature,
String? avatar,
});
}
/// @nodoc
class __$$UserProfileImplCopyWithImpl<$Res>
extends _$UserProfileCopyWithImpl<$Res, _$UserProfileImpl>
implements _$$UserProfileImplCopyWith<$Res> {
__$$UserProfileImplCopyWithImpl(
_$UserProfileImpl _value,
$Res Function(_$UserProfileImpl) _then,
) : super(_value, _then);
/// Create a copy of UserProfile
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? id = null,
Object? username = null,
Object? nickname = null,
Object? signature = null,
Object? avatar = freezed,
}) {
return _then(
_$UserProfileImpl(
id: null == id
? _value.id
: id // ignore: cast_nullable_to_non_nullable
as String,
username: null == username
? _value.username
: username // ignore: cast_nullable_to_non_nullable
as String,
nickname: null == nickname
? _value.nickname
: nickname // ignore: cast_nullable_to_non_nullable
as String,
signature: null == signature
? _value.signature
: signature // ignore: cast_nullable_to_non_nullable
as String,
avatar: freezed == avatar
? _value.avatar
: avatar // ignore: cast_nullable_to_non_nullable
as String?,
),
);
}
}
/// @nodoc
@JsonSerializable()
class _$UserProfileImpl extends _UserProfile {
const _$UserProfileImpl({
@JsonKey(fromJson: _idToString) required this.id,
this.username = '',
this.nickname = '',
this.signature = '',
this.avatar,
}) : super._();
factory _$UserProfileImpl.fromJson(Map<String, dynamic> json) =>
_$$UserProfileImplFromJson(json);
@override
@JsonKey(fromJson: _idToString)
final String id;
@override
@JsonKey()
final String username;
@override
@JsonKey()
final String nickname;
@override
@JsonKey()
final String signature;
@override
final String? avatar;
@override
String toString() {
return 'UserProfile(id: $id, username: $username, nickname: $nickname, signature: $signature, avatar: $avatar)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$UserProfileImpl &&
(identical(other.id, id) || other.id == id) &&
(identical(other.username, username) ||
other.username == username) &&
(identical(other.nickname, nickname) ||
other.nickname == nickname) &&
(identical(other.signature, signature) ||
other.signature == signature) &&
(identical(other.avatar, avatar) || other.avatar == avatar));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode =>
Object.hash(runtimeType, id, username, nickname, signature, avatar);
/// Create a copy of UserProfile
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@override
@pragma('vm:prefer-inline')
_$$UserProfileImplCopyWith<_$UserProfileImpl> get copyWith =>
__$$UserProfileImplCopyWithImpl<_$UserProfileImpl>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$UserProfileImplToJson(this);
}
}
abstract class _UserProfile extends UserProfile {
const factory _UserProfile({
@JsonKey(fromJson: _idToString) required final String id,
final String username,
final String nickname,
final String signature,
final String? avatar,
}) = _$UserProfileImpl;
const _UserProfile._() : super._();
factory _UserProfile.fromJson(Map<String, dynamic> json) =
_$UserProfileImpl.fromJson;
@override
@JsonKey(fromJson: _idToString)
String get id;
@override
String get username;
@override
String get nickname;
@override
String get signature;
@override
String? get avatar;
/// Create a copy of UserProfile
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
_$$UserProfileImplCopyWith<_$UserProfileImpl> get copyWith =>
throw _privateConstructorUsedError;
}
ProfileState _$ProfileStateFromJson(Map<String, dynamic> json) {
return _ProfileState.fromJson(json);
}
/// @nodoc
mixin _$ProfileState {
UserProfile? get profile => throw _privateConstructorUsedError;
bool get loading => throw _privateConstructorUsedError;
bool get saving => throw _privateConstructorUsedError;
String? get alert => throw _privateConstructorUsedError;
ProfileIssue? get issue => throw _privateConstructorUsedError;
/// Serializes this ProfileState to a JSON map.
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
/// Create a copy of ProfileState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
$ProfileStateCopyWith<ProfileState> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $ProfileStateCopyWith<$Res> {
factory $ProfileStateCopyWith(
ProfileState value,
$Res Function(ProfileState) then,
) = _$ProfileStateCopyWithImpl<$Res, ProfileState>;
@useResult
$Res call({
UserProfile? profile,
bool loading,
bool saving,
String? alert,
ProfileIssue? issue,
});
$UserProfileCopyWith<$Res>? get profile;
}
/// @nodoc
class _$ProfileStateCopyWithImpl<$Res, $Val extends ProfileState>
implements $ProfileStateCopyWith<$Res> {
_$ProfileStateCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
/// Create a copy of ProfileState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? profile = freezed,
Object? loading = null,
Object? saving = null,
Object? alert = freezed,
Object? issue = freezed,
}) {
return _then(
_value.copyWith(
profile: freezed == profile
? _value.profile
: profile // ignore: cast_nullable_to_non_nullable
as UserProfile?,
loading: null == loading
? _value.loading
: loading // ignore: cast_nullable_to_non_nullable
as bool,
saving: null == saving
? _value.saving
: saving // ignore: cast_nullable_to_non_nullable
as bool,
alert: freezed == alert
? _value.alert
: alert // ignore: cast_nullable_to_non_nullable
as String?,
issue: freezed == issue
? _value.issue
: issue // ignore: cast_nullable_to_non_nullable
as ProfileIssue?,
)
as $Val,
);
}
/// Create a copy of ProfileState
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$UserProfileCopyWith<$Res>? get profile {
if (_value.profile == null) {
return null;
}
return $UserProfileCopyWith<$Res>(_value.profile!, (value) {
return _then(_value.copyWith(profile: value) as $Val);
});
}
}
/// @nodoc
abstract class _$$ProfileStateImplCopyWith<$Res>
implements $ProfileStateCopyWith<$Res> {
factory _$$ProfileStateImplCopyWith(
_$ProfileStateImpl value,
$Res Function(_$ProfileStateImpl) then,
) = __$$ProfileStateImplCopyWithImpl<$Res>;
@override
@useResult
$Res call({
UserProfile? profile,
bool loading,
bool saving,
String? alert,
ProfileIssue? issue,
});
@override
$UserProfileCopyWith<$Res>? get profile;
}
/// @nodoc
class __$$ProfileStateImplCopyWithImpl<$Res>
extends _$ProfileStateCopyWithImpl<$Res, _$ProfileStateImpl>
implements _$$ProfileStateImplCopyWith<$Res> {
__$$ProfileStateImplCopyWithImpl(
_$ProfileStateImpl _value,
$Res Function(_$ProfileStateImpl) _then,
) : super(_value, _then);
/// Create a copy of ProfileState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? profile = freezed,
Object? loading = null,
Object? saving = null,
Object? alert = freezed,
Object? issue = freezed,
}) {
return _then(
_$ProfileStateImpl(
profile: freezed == profile
? _value.profile
: profile // ignore: cast_nullable_to_non_nullable
as UserProfile?,
loading: null == loading
? _value.loading
: loading // ignore: cast_nullable_to_non_nullable
as bool,
saving: null == saving
? _value.saving
: saving // ignore: cast_nullable_to_non_nullable
as bool,
alert: freezed == alert
? _value.alert
: alert // ignore: cast_nullable_to_non_nullable
as String?,
issue: freezed == issue
? _value.issue
: issue // ignore: cast_nullable_to_non_nullable
as ProfileIssue?,
),
);
}
}
/// @nodoc
@JsonSerializable()
class _$ProfileStateImpl implements _ProfileState {
const _$ProfileStateImpl({
this.profile,
this.loading = true,
this.saving = false,
this.alert,
this.issue,
});
factory _$ProfileStateImpl.fromJson(Map<String, dynamic> json) =>
_$$ProfileStateImplFromJson(json);
@override
final UserProfile? profile;
@override
@JsonKey()
final bool loading;
@override
@JsonKey()
final bool saving;
@override
final String? alert;
@override
final ProfileIssue? issue;
@override
String toString() {
return 'ProfileState(profile: $profile, loading: $loading, saving: $saving, alert: $alert, issue: $issue)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$ProfileStateImpl &&
(identical(other.profile, profile) || other.profile == profile) &&
(identical(other.loading, loading) || other.loading == loading) &&
(identical(other.saving, saving) || other.saving == saving) &&
(identical(other.alert, alert) || other.alert == alert) &&
(identical(other.issue, issue) || other.issue == issue));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode =>
Object.hash(runtimeType, profile, loading, saving, alert, issue);
/// Create a copy of ProfileState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@override
@pragma('vm:prefer-inline')
_$$ProfileStateImplCopyWith<_$ProfileStateImpl> get copyWith =>
__$$ProfileStateImplCopyWithImpl<_$ProfileStateImpl>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$ProfileStateImplToJson(this);
}
}
abstract class _ProfileState implements ProfileState {
const factory _ProfileState({
final UserProfile? profile,
final bool loading,
final bool saving,
final String? alert,
final ProfileIssue? issue,
}) = _$ProfileStateImpl;
factory _ProfileState.fromJson(Map<String, dynamic> json) =
_$ProfileStateImpl.fromJson;
@override
UserProfile? get profile;
@override
bool get loading;
@override
bool get saving;
@override
String? get alert;
@override
ProfileIssue? get issue;
/// Create a copy of ProfileState
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
_$$ProfileStateImplCopyWith<_$ProfileStateImpl> get copyWith =>
throw _privateConstructorUsedError;
}
@@ -0,0 +1,52 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'profile_models.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$UserProfileImpl _$$UserProfileImplFromJson(Map<String, dynamic> json) =>
_$UserProfileImpl(
id: _idToString(json['id']),
username: json['username'] as String? ?? '',
nickname: json['nickname'] as String? ?? '',
signature: json['signature'] as String? ?? '',
avatar: json['avatar'] as String?,
);
Map<String, dynamic> _$$UserProfileImplToJson(_$UserProfileImpl instance) =>
<String, dynamic>{
'id': instance.id,
'username': instance.username,
'nickname': instance.nickname,
'signature': instance.signature,
'avatar': instance.avatar,
};
_$ProfileStateImpl _$$ProfileStateImplFromJson(Map<String, dynamic> json) =>
_$ProfileStateImpl(
profile: json['profile'] == null
? null
: UserProfile.fromJson(json['profile'] as Map<String, dynamic>),
loading: json['loading'] as bool? ?? true,
saving: json['saving'] as bool? ?? false,
alert: json['alert'] as String?,
issue: $enumDecodeNullable(_$ProfileIssueEnumMap, json['issue']),
);
Map<String, dynamic> _$$ProfileStateImplToJson(_$ProfileStateImpl instance) =>
<String, dynamic>{
'profile': instance.profile,
'loading': instance.loading,
'saving': instance.saving,
'alert': instance.alert,
'issue': _$ProfileIssueEnumMap[instance.issue],
};
const _$ProfileIssueEnumMap = {
ProfileIssue.nicknameInvalid: 'nicknameInvalid',
ProfileIssue.signatureInvalid: 'signatureInvalid',
ProfileIssue.avatarTooLarge: 'avatarTooLarge',
ProfileIssue.avatarUnsupported: 'avatarUnsupported',
};
@@ -0,0 +1,7 @@
import 'profile_models.dart';
abstract class ProfileRepository {
Future<UserProfile> load();
Future<UserProfile> save(String nickname, String signature);
Future<UserProfile?> chooseAvatar();
}
@@ -0,0 +1,44 @@
import 'package:cupertino_ui/cupertino_ui.dart';
import '../../../core/network/cached_network_image.dart';
import '../../../core/widgets/feature_ui.dart';
class ProfileAvatar extends StatelessWidget {
const ProfileAvatar({this.url, this.name = '', this.size = 58, super.key});
final String? url;
final String name;
final double size;
@override
Widget build(BuildContext context) {
final fallback = Center(
child: Text(
name.isEmpty ? 'U' : name.characters.first,
style: TextStyle(
fontSize: size * 0.4,
fontWeight: FontWeight.w700,
color: CupertinoColors.white,
),
),
);
return ClipOval(
child: Container(
width: size,
height: size,
decoration: const BoxDecoration(
gradient: LinearGradient(colors: [AppColors.green, AppColors.blue]),
),
child: url == null || url!.isEmpty
? fallback
: Image(
image: cachedNetworkImage(url!),
fit: BoxFit.cover,
frameBuilder: (_, child, frame, synchronous) =>
frame == null && !synchronous ? fallback : child,
errorBuilder: (_, _, _) => fallback,
),
),
);
}
}
@@ -0,0 +1,86 @@
import 'dart:async';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../../core/network/error_message.dart';
import '../data/profile_repository_impl.dart';
import '../domain/profile_models.dart';
part 'profile_controller.g.dart';
@riverpod
class ProfileController extends _$ProfileController {
bool _active = true;
int _generation = 0;
@override
ProfileState build() {
_active = true;
ref.onDispose(() => _active = false);
unawaited(Future<void>.microtask(reload));
return const ProfileState();
}
Future<void> reload() async {
if (!_active || state.saving) return;
final generation = ++_generation;
state = state.copyWith(loading: true, alert: null, issue: null);
try {
final profile = await ref.read(profileRepositoryProvider).load();
if (_active && generation == _generation) {
state = state.copyWith(profile: profile, loading: false);
}
} catch (_) {
if (_active && generation == _generation) {
state = state.copyWith(loading: false);
}
}
}
Future<bool> save(String nickname, String signature) async {
if (state.saving) return false;
final name = nickname.trim();
if (name.isEmpty || name.length > 64) {
state = state.copyWith(issue: ProfileIssue.nicknameInvalid);
return false;
}
if (signature.trim().length > 200) {
state = state.copyWith(issue: ProfileIssue.signatureInvalid);
return false;
}
return _write(
() => ref.read(profileRepositoryProvider).save(name, signature.trim()),
);
}
Future<void> changeAvatar() async {
await _write(() => ref.read(profileRepositoryProvider).chooseAvatar());
}
Future<bool> _write(Future<UserProfile?> Function() action) async {
if (state.saving) return false;
++_generation;
state = state.copyWith(
saving: true,
loading: false,
alert: null,
issue: null,
);
try {
final profile = await action();
if (!_active) return false;
state = state.copyWith(profile: profile ?? state.profile, saving: false);
return profile != null;
} on ProfileInputException catch (error) {
if (_active) state = state.copyWith(saving: false, issue: error.issue);
return false;
} catch (error) {
if (_active) {
state = state.copyWith(saving: false, alert: userMessageOf(error));
}
return false;
}
}
void consumeAlert() => state = state.copyWith(alert: null, issue: null);
}
@@ -0,0 +1,26 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'profile_controller.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
String _$profileControllerHash() => r'dbdebff74e6f706416c46f5dff9007f99c67c4ff';
/// See also [ProfileController].
@ProviderFor(ProfileController)
final profileControllerProvider =
AutoDisposeNotifierProvider<ProfileController, ProfileState>.internal(
ProfileController.new,
name: r'profileControllerProvider',
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
? null
: _$profileControllerHash,
dependencies: null,
allTransitiveDependencies: null,
);
typedef _$ProfileController = AutoDisposeNotifier<ProfileState>;
// ignore_for_file: type=lint
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
@@ -1,144 +1,182 @@
import 'package:cupertino_ui/cupertino_ui.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:ttstd_family_care/app/theme/dark_mode.dart';
import 'package:ttstd_family_care/core/widgets/app_page_scaffold.dart';
import '../../../app/theme/dark_mode.dart';
import '../../../core/widgets/app_page_scaffold.dart';
import '../../../core/widgets/feature_ui.dart';
import '../../../core/widgets/settings_ui.dart';
import '../../../l10n/app_localizations.dart';
import '../domain/profile_models.dart';
import 'profile_avatar.dart';
import 'profile_controller.dart';
/// 个人资料页(我的 → 编辑资料)。
///
/// 头像、昵称、个性签名的独立展示页面;从「我的」页头部的编辑资料入口进入。
class ProfileEditPage extends StatelessWidget {
class ProfileEditPage extends ConsumerStatefulWidget {
const ProfileEditPage({super.key});
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
ConsumerState<ProfileEditPage> createState() => _ProfileEditPageState();
}
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) {
if (didPop) return;
if (context.canPop()) {
context.pop();
} else {
context.go('/profile');
}
},
child: AppPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text(l10n.profileInfo),
leading: CupertinoButton(
padding: EdgeInsets.zero,
child: const Icon(CupertinoIcons.back),
onPressed: () => context.pop(),
class _ProfileEditPageState extends ConsumerState<ProfileEditPage> {
final _nickname = TextEditingController();
final _signature = TextEditingController();
bool _initialized = false;
@override
void initState() {
super.initState();
_fill(ref.read(profileControllerProvider).profile);
}
void _fill(UserProfile? profile) {
if (_initialized || profile == null) return;
_nickname.text = profile.nickname;
_signature.text = profile.signature;
_initialized = true;
}
@override
void dispose() {
_nickname.dispose();
_signature.dispose();
super.dispose();
}
void _alert(String message) {
showCupertinoDialog<void>(
context: context,
builder: (context) => CupertinoAlertDialog(
content: Text(message),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.of(context).pop(),
child: Text(AppLocalizations.of(context).commonConfirm),
),
),
child: SafeArea(
child: ListView(
padding: const EdgeInsets.only(bottom: 24),
children: [
SectionTitle(l10n.profileInfo),
CardBox(
padding: EdgeInsets.zero,
child: Column(
children: [
_infoRow(
context,
'🖼️',
AppColors.purple,
l10n.piAvatar,
const _AvatarPreview(),
),
const AppDivider(),
_infoRow(
context,
'📛',
AppColors.blue,
l10n.piName,
const Text('用户名'),
),
const AppDivider(),
_infoRow(
context,
'✍️',
AppColors.orange,
l10n.piSign,
const Text('热爱生活'),
),
],
),
),
],
),
),
],
),
);
}
Widget _infoRow(
BuildContext context,
String emoji,
Color color,
String label,
Widget trailing,
) =>
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
child: Row(
children: [
Container(
width: 36,
height: 36,
decoration:
BoxDecoration(color: color, borderRadius: BorderRadius.circular(11)),
child: Center(child: Text(emoji, style: const TextStyle(fontSize: 17))),
),
const SizedBox(width: 12),
Text(
label,
style: TextStyle(
fontSize: 14.5,
fontWeight: FontWeight.w600,
color: DarkMode.color(context, AppColors.ink),
),
),
const Spacer(),
DefaultTextStyle.merge(
style: TextStyle(fontSize: 13, color: DarkMode.color(context, AppColors.sub)),
child: trailing,
),
],
),
);
}
/// 资料页头像预览(与「我的」页头部样式一致)。
class _AvatarPreview extends StatelessWidget {
const _AvatarPreview();
@override
Widget build(BuildContext context) => Container(
width: 34,
height: 34,
decoration: const BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
colors: [AppColors.green, AppColors.blue],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
final state = ref.watch(profileControllerProvider);
ref.listen(profileControllerProvider, (previous, next) {
_fill(next.profile);
if (next.alert == null && next.issue == null) return;
final message = switch (next.issue) {
ProfileIssue.nicknameInvalid => l10n.profileNicknameInvalid,
ProfileIssue.signatureInvalid => l10n.profileSignatureInvalid,
ProfileIssue.avatarTooLarge => l10n.profileAvatarTooLarge,
ProfileIssue.avatarUnsupported => l10n.profileAvatarUnsupported,
null => next.alert!,
};
ref.read(profileControllerProvider.notifier).consumeAlert();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _alert(message);
});
});
final profile = state.profile;
return AppPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text(l10n.profileEdit),
leading: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: state.saving ? null : () => context.pop(),
child: const Icon(CupertinoIcons.back),
),
child: const Center(
child: Text(
'U',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w700,
color: CupertinoColors.white,
),
),
trailing: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: state.saving || profile == null
? null
: () async {
final saved = await ref
.read(profileControllerProvider.notifier)
.save(_nickname.text, _signature.text);
if (saved && context.mounted) context.pop();
},
child: state.saving
? const CupertinoActivityIndicator()
: Text(l10n.commonSave),
),
);
}
),
child: SafeArea(
child: profile == null
? Center(
child: state.loading
? const CupertinoActivityIndicator()
: CupertinoButton(
onPressed: ref
.read(profileControllerProvider.notifier)
.reload,
child: Text(l10n.commonRetry),
),
)
: ListView(
padding: const EdgeInsets.only(top: 16, bottom: 32),
children: [
Center(
child: CupertinoButton(
onPressed: state.saving
? null
: ref
.read(profileControllerProvider.notifier)
.changeAvatar,
child: Column(
children: [
ProfileAvatar(
url: profile.avatar,
name: profile.displayName,
size: 84,
),
const SizedBox(height: 10),
Text(l10n.profileChangeAvatar),
],
),
),
),
LabeledField(
label: l10n.piName,
controller: _nickname,
maxLength: 64,
enabled: !state.saving,
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.piSign,
style: TextStyle(
color: DarkMode.color(context, AppColors.sub),
),
),
const SizedBox(height: 6),
CupertinoTextField(
controller: _signature,
maxLength: 200,
maxLines: 3,
enabled: !state.saving,
padding: const EdgeInsets.all(14),
style: TextStyle(
color: DarkMode.color(context, AppColors.ink),
),
decoration: BoxDecoration(
color: DarkMode.color(context, AppColors.card),
borderRadius: BorderRadius.circular(12),
),
),
],
),
),
],
),
),
);
}
}
+314 -130
View File
@@ -9,6 +9,8 @@ import '../../../features/device/data/device_providers.dart';
import '../../../features/device/domain/device_models.dart';
import '../../../l10n/app_localizations.dart';
import '../../auth/presentation/auth_controller.dart';
import 'profile_avatar.dart';
import 'profile_controller.dart';
/// 我的 Tab 内容(特性模块:profile / presentation)。
///
@@ -20,6 +22,8 @@ class ProfileTab extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final l10n = AppLocalizations.of(context);
final profileState = ref.watch(profileControllerProvider);
final profile = profileState.profile;
return AppPageScaffold(
child: SafeArea(
@@ -31,23 +35,30 @@ class ProfileTab extends ConsumerWidget {
padding: const EdgeInsets.all(18),
child: Row(
children: [
Container(
width: 58,
height: 58,
decoration: const BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
colors: [AppColors.green, AppColors.blue],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
),
child: const Center(
child: Text('U',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w700,
color: CupertinoColors.white)),
GestureDetector(
onTap: profileState.saving
? null
: () => context.push('/profile/edit'),
child: Stack(
alignment: Alignment.center,
children: [
ProfileAvatar(
url: profile?.avatar,
name: profile?.displayName ?? '',
),
if (profileState.loading && profile == null)
const Positioned.fill(
child: DecoratedBox(
decoration: BoxDecoration(
color: Color(0x55000000),
shape: BoxShape.circle,
),
child: CupertinoActivityIndicator(
color: CupertinoColors.white,
),
),
),
],
),
),
const SizedBox(width: 14),
@@ -55,33 +66,70 @@ class ProfileTab extends ConsumerWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('用户名',
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w700,
color: DarkMode.color(context, AppColors.ink))),
Text(
profile?.displayName.isNotEmpty == true
? profile!.displayName
: l10n.piName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w700,
color: DarkMode.color(context, AppColors.ink),
),
),
const SizedBox(height: 4),
Text('ID: u_8821 · 平板管家 Pro',
Text(
profile == null ? '' : 'ID: ${profile.id}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12.5,
color: DarkMode.color(context, AppColors.sub),
),
),
const SizedBox(height: 4),
// Reserve two signature lines before the profile arrives.
SizedBox(
height:
(MediaQuery.textScalerOf(context).scale(12) * 1.3)
.ceilToDouble() *
2,
child: Text(
profile?.signature ?? '',
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12.5,
color: DarkMode.color(context, AppColors.sub))),
fontSize: 12,
height: 1.3,
color: DarkMode.color(context, AppColors.sub),
),
),
),
],
),
),
GestureDetector(
onTap: () => context.push('/profile/edit'),
onTap: profileState.saving
? null
: () => context.push('/profile/edit'),
child: Container(
padding:
const EdgeInsets.symmetric(horizontal: 14, vertical: 7),
padding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 7,
),
decoration: BoxDecoration(
color: AppColors.green.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(20),
),
child: Text(l10n.profileEdit,
style: const TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: AppColors.green)),
child: Text(
l10n.profileEdit,
style: const TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: AppColors.green,
),
),
),
),
],
@@ -100,16 +148,40 @@ class ProfileTab extends ConsumerWidget {
padding: EdgeInsets.zero,
child: Column(
children: [
_settingRow(context, '🔔', AppColors.teal, l10n.setNotify, '消息、设备状态提醒'),
_settingRow(
context,
'🔔',
AppColors.teal,
l10n.setNotify,
'消息、设备状态提醒',
),
const AppDivider(),
_settingRow(context, '🔒', const Color(0xFF22C55E), l10n.setPrivacy, '定位、相册、权限管理'),
_settingRow(
context,
'🔒',
const Color(0xFF22C55E),
l10n.setPrivacy,
'定位、相册、权限管理',
),
const AppDivider(),
_settingRow(context, '🛡️', AppColors.red, l10n.setSecurity, '登录设备、密码',
onTap: () => context.push('/security')),
_settingRow(
context,
'🛡️',
AppColors.red,
l10n.setSecurity,
'登录设备、密码',
onTap: () => context.push('/security'),
),
const AppDivider(),
_settingRow(context, '❓', AppColors.gray, l10n.setHelp, null),
const AppDivider(),
_settingRow(context, 'ℹ️', const Color(0xFF64748B), l10n.setAbout, '平板管家 v3.2.1'),
_settingRow(
context,
'ℹ️',
const Color(0xFF64748B),
l10n.setAbout,
'平板管家 v3.2.1',
),
],
),
),
@@ -126,7 +198,11 @@ class ProfileTab extends ConsumerWidget {
color: DarkMode.color(context, AppColors.card),
borderRadius: BorderRadius.circular(14),
boxShadow: const [
BoxShadow(color: Color(0x14141E3C), blurRadius: 16, offset: Offset(0, 4)),
BoxShadow(
color: Color(0x14141E3C),
blurRadius: 16,
offset: Offset(0, 4),
),
],
),
child: Center(
@@ -152,7 +228,10 @@ class ProfileTab extends ConsumerWidget {
}
Widget _boundDeviceCard(
BuildContext context, WidgetRef ref, AppLocalizations l10n) {
BuildContext context,
WidgetRef ref,
AppLocalizations l10n,
) {
final devicesAsync = ref.watch(myDevicesProvider);
final device = ref.watch(currentDeviceProvider);
return CardBox(
@@ -162,116 +241,221 @@ class ProfileTab extends ConsumerWidget {
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
child: devicesAsync.when(
loading: () => const Padding(
padding: EdgeInsets.symmetric(vertical: 24),
child: Center(child: CupertinoActivityIndicator()),
),
error: (e, _) => Padding(
padding: const EdgeInsets.all(16),
child: Text('${l10n.deviceLoadFailed}:$e',
style: TextStyle(fontSize: 12, color: DarkMode.color(context, AppColors.sub))),
),
data: (_) {
if (device == null) {
// 无绑定设备时也可点击进入设备管理页添加设备。
child: SizedBox(
height:
28 +
((MediaQuery.textScalerOf(context).scale(14.5) * 1.3)
.ceilToDouble() +
2 +
(MediaQuery.textScalerOf(context).scale(12) * 1.3)
.ceilToDouble())
.clamp(36.0, double.infinity),
child: devicesAsync.when(
loading: () => const Padding(
padding: EdgeInsets.symmetric(vertical: 24),
child: Center(child: CupertinoActivityIndicator()),
),
error: (e, _) => Padding(
padding: const EdgeInsets.all(16),
child: Text(
'${l10n.deviceLoadFailed}:$e',
style: TextStyle(
fontSize: 12,
color: DarkMode.color(context, AppColors.sub),
),
),
),
data: (_) {
if (device == null) {
// 无绑定设备时也可点击进入设备管理页添加设备。
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => context.push('/device/manage'),
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Expanded(
child: Text(
l10n.deviceNone,
style: TextStyle(
fontSize: 13,
color: DarkMode.color(context, AppColors.sub),
),
),
),
Text(
'${l10n.deviceManageAdd} ›',
style: const TextStyle(
fontSize: 13,
color: AppColors.green,
),
),
],
),
),
);
}
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => context.push('/device/manage'),
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Expanded(
child: Text(l10n.deviceNone,
style: TextStyle(fontSize: 13, color: DarkMode.color(context, AppColors.sub))),
),
Text('${l10n.deviceManageAdd} ›',
style: const TextStyle(fontSize: 13, color: AppColors.green)),
],
),
),
child: _deviceCard(context, device, l10n),
);
}
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => context.push('/device/manage'),
child: _deviceCard(context, device, l10n),
);
},
},
),
),
);
}
Widget _deviceCard(BuildContext context, DeviceBrief device, AppLocalizations l10n) {
Widget _deviceCard(
BuildContext context,
DeviceBrief device,
AppLocalizations l10n,
) {
final status = device.isOnline ? l10n.deviceOnline : l10n.deviceOffline;
final sub = device.snModel?.isNotEmpty == true
? '$status · ${device.snModel}'
: status;
return _deviceRow(context, '📱',
device.isOnline ? AppColors.green : DarkMode.color(context, AppColors.track),
device.snName?.isNotEmpty == true ? device.snName! : device.serialno, sub,
l10n.deviceManage);
return _deviceRow(
context,
'📱',
device.isOnline
? AppColors.green
: DarkMode.color(context, AppColors.track),
device.snName?.isNotEmpty == true ? device.snName! : device.serialno,
sub,
l10n.deviceManage,
);
}
Widget _deviceRow(BuildContext context, String emoji, Color color, String title, String sub, String? action) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
child: Row(
children: [
Container(
width: 36,
height: 36,
decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(11)),
child: Center(child: Text(emoji, style: const TextStyle(fontSize: 17))),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: TextStyle(fontSize: 14.5, fontWeight: FontWeight.w600, color: DarkMode.color(context, AppColors.ink))),
const SizedBox(height: 2),
Text(sub, style: TextStyle(fontSize: 12, color: DarkMode.color(context, AppColors.sub))),
],
),
),
if (action != null)
Text('$action ›', style: TextStyle(fontSize: 13, color: DarkMode.color(context, AppColors.sub)))
else
const Text('›', style: TextStyle(fontSize: 16, color: Color(0xFFCBD2DC))),
],
Widget _deviceRow(
BuildContext context,
String emoji,
Color color,
String title,
String sub,
String? action,
) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
child: Row(
children: [
Container(
width: 36,
height: 36,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(11),
),
child: Center(
child: Text(emoji, style: const TextStyle(fontSize: 17)),
),
),
);
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14.5,
height: 1.3,
fontWeight: FontWeight.w600,
color: DarkMode.color(context, AppColors.ink),
),
),
const SizedBox(height: 2),
Text(
sub,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
height: 1.3,
color: DarkMode.color(context, AppColors.sub),
),
),
],
),
),
if (action != null)
Text(
'$action ›',
style: TextStyle(
fontSize: 13,
color: DarkMode.color(context, AppColors.sub),
),
)
else
const Text(
'›',
style: TextStyle(fontSize: 16, color: Color(0xFFCBD2DC)),
),
],
),
);
Widget _settingRow(BuildContext context, String emoji, Color color, String label, String? sub,
{VoidCallback? onTap}) {
Widget _settingRow(
BuildContext context,
String emoji,
Color color,
String label,
String? sub, {
VoidCallback? onTap,
}) {
final row = Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 13),
child: Row(
children: [
Container(
width: 36,
height: 36,
decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(11)),
child: Center(child: Text(emoji, style: const TextStyle(fontSize: 17))),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 13),
child: Row(
children: [
Container(
width: 36,
height: 36,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(11),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: TextStyle(fontSize: 14.5, fontWeight: FontWeight.w600, color: DarkMode.color(context, AppColors.ink))),
if (sub != null) ...[
const SizedBox(height: 2),
Text(sub, style: TextStyle(fontSize: 12, color: DarkMode.color(context, AppColors.sub))),
],
child: Center(
child: Text(emoji, style: const TextStyle(fontSize: 17)),
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: TextStyle(
fontSize: 14.5,
fontWeight: FontWeight.w600,
color: DarkMode.color(context, AppColors.ink),
),
),
if (sub != null) ...[
const SizedBox(height: 2),
Text(
sub,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
height: 1.3,
color: DarkMode.color(context, AppColors.sub),
),
),
],
),
],
),
const Text('›', style: TextStyle(fontSize: 16, color: Color(0xFFCBD2DC))),
],
),
);
),
const Text(
'›',
style: TextStyle(fontSize: 16, color: Color(0xFFCBD2DC)),
),
],
),
);
if (onTap == null) return row;
return GestureDetector(
behavior: HitTestBehavior.opaque,