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

+14
View File
@@ -123,6 +123,7 @@ class DeviceApi {
try {
final data = await DioClient.get(
'v1/client/sn/policy',
allowStale: true,
queryParameters: {'sn': sn},
);
return data is Map<String, dynamic> ? DevicePolicy.fromJson(data) : null;
@@ -131,6 +132,15 @@ class DeviceApi {
}
}
/// 读取本地策略快照,不发起网络请求。
Future<DevicePolicy?> getCachedPolicy(String sn) async {
final data = await DioClient.readCachedGet(
'v1/client/sn/policy',
queryParameters: {'sn': sn},
);
return data is Map<String, dynamic> ? DevicePolicy.fromJson(data) : null;
}
/// 单独设置某个策略开关。
///
/// 对应后台 `PUT /api/v1/client/sn/policy/toggle`,请求体 `{field, value}`。
@@ -142,6 +152,10 @@ class DeviceApi {
data: {'field': field, 'value': value},
);
debugPrint('[DeviceApi] togglePolicy sn=$sn field=$field value=$value data=$data');
await DioClient.invalidateReadCache(
'v1/client/sn/policy',
queryParameters: {'sn': sn},
);
return null;
} on ApiException catch (e) {
debugPrint('[DeviceApi] togglePolicy sn=$sn field=$field value=$value failed: ${e.message}');
@@ -37,6 +37,9 @@ class DeviceRepositoryImpl implements DeviceRepository {
@override
Future<DevicePolicy?> getPolicy(String sn) => _api.getPolicy(sn);
@override
Future<DevicePolicy?> getCachedPolicy(String sn) => _api.getCachedPolicy(sn);
@override
Future<String?> togglePolicy(String sn, String field, int value) =>
_api.togglePolicy(sn, field, value);
@@ -32,6 +32,9 @@ abstract class DeviceRepository {
/// 已绑定设备策略信息(功能开关),无记录时为 null。
Future<DevicePolicy?> getPolicy(String sn);
/// 读取当前账号、设备的上一次策略缓存。
Future<DevicePolicy?> getCachedPolicy(String sn);
/// 单独设置某个策略开关(field 为策略字段名,value 为 0/1)。
///
/// 成功返回 null;失败返回错误提示。
+27 -8
View File
@@ -24,9 +24,19 @@ class HomePage extends StatefulWidget {
class _HomePageState extends State<HomePage> {
final _dragPage = ValueNotifier<double?>(null);
final _visibleIndex = ValueNotifier<int?>(null);
int? _tabPointer;
Offset _tabPointerStart = Offset.zero;
@override
void didUpdateWidget(covariant HomePage oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.navigationShell.currentIndex !=
oldWidget.navigationShell.currentIndex) {
_visibleIndex.value = null;
}
}
void _finishTabDrag(PointerEvent event) {
if (event.pointer != _tabPointer) return;
_tabPointer = null;
@@ -36,6 +46,7 @@ class _HomePageState extends State<HomePage> {
@override
void dispose() {
_dragPage.dispose();
_visibleIndex.dispose();
super.dispose();
}
@@ -75,7 +86,11 @@ class _HomePageState extends State<HomePage> {
resizeToAvoidBottomInset: false,
child: Stack(
children: [
HomeTabDragScope(page: _dragPage, child: navigationShell),
HomeTabDragScope(
page: _dragPage,
visibleIndex: _visibleIndex,
child: navigationShell,
),
Align(
alignment: Alignment.bottomCenter,
child: SafeArea(
@@ -118,13 +133,17 @@ class _HomePageState extends State<HomePage> {
// GlassTabBar 仍读取 Flutter SDK 的 Cupertino 主题。
// ignore: deprecated_member_use
child: CupertinoUiCompatibilityBridge(
child: GlassTabBar.bottom(
selectedIndex: index,
onTabSelected: navigationShell.goBranch,
horizontalPadding: tabBarMargin,
verticalPadding: 0,
iconSize: 26,
tabs: tabs,
child: ValueListenableBuilder<int?>(
valueListenable: _visibleIndex,
builder: (context, visibleIndex, _) =>
GlassTabBar.bottom(
selectedIndex: visibleIndex ?? index,
onTabSelected: navigationShell.goBranch,
horizontalPadding: tabBarMargin,
verticalPadding: 0,
iconSize: 26,
tabs: tabs,
),
),
),
);
+18 -3
View File
@@ -239,8 +239,10 @@ class HomeTab extends ConsumerWidget {
Container(
width: 64,
height: 64,
decoration: const BoxDecoration(
color: CupertinoColors.white, shape: BoxShape.circle),
decoration: BoxDecoration(
color: DarkMode.color(context, AppColors.card),
shape: BoxShape.circle,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
@@ -274,7 +276,20 @@ class HomeTab extends ConsumerWidget {
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
SizedBox(width: 42, child: Text(name, style: const TextStyle(fontSize: 12, color: Color(0xFF4B5563)))),
SizedBox(
width: 42,
child: Text(
name,
style: TextStyle(
fontSize: 12,
color: DarkMode.tone(
context,
const Color(0xFF4B5563),
DarkMode.color(context, AppColors.ink),
),
),
),
),
Expanded(
child: Container(
height: 7,
@@ -4,12 +4,19 @@ import 'package:go_router/go_router.dart';
/// Fractional page selected by the bottom bar while a pointer is dragging.
class HomeTabDragScope extends InheritedWidget {
const HomeTabDragScope({required this.page, required super.child, super.key});
const HomeTabDragScope({
required this.page,
required this.visibleIndex,
required super.child,
super.key,
});
final ValueNotifier<double?> page;
final ValueNotifier<int?> visibleIndex;
@override
bool updateShouldNotify(HomeTabDragScope oldWidget) => page != oldWidget.page;
bool updateShouldNotify(HomeTabDragScope oldWidget) =>
page != oldWidget.page || visibleIndex != oldWidget.visibleIndex;
}
/// Displays the shell's existing branch navigators as swipeable pages.
@@ -34,13 +41,15 @@ class _HomeTabPagerState extends State<HomeTabPager> {
);
ValueNotifier<double?>? _dragPage;
Drag? _tabDrag;
ValueNotifier<int?>? _visibleIndex;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final page = context
.dependOnInheritedWidgetOfExactType<HomeTabDragScope>()
?.page;
final scope = context
.dependOnInheritedWidgetOfExactType<HomeTabDragScope>();
_visibleIndex = scope?.visibleIndex;
final page = scope?.page;
if (page == _dragPage) return;
_dragPage?.removeListener(_updateTabDrag);
_dragPage = page;
@@ -81,7 +90,9 @@ class _HomeTabPagerState extends State<HomeTabPager> {
void didUpdateWidget(covariant HomeTabPager oldWidget) {
super.didUpdateWidget(oldWidget);
final index = widget.navigationShell.currentIndex;
if (index != oldWidget.navigationShell.currentIndex) _animateToIndex(index);
if (index != oldWidget.navigationShell.currentIndex) {
_animateToIndex(index);
}
}
void _animateToIndex(int index) {
@@ -118,6 +129,9 @@ class _HomeTabPagerState extends State<HomeTabPager> {
},
child: PageView(
controller: _controller,
// Update the bar at the page midpoint, without waiting for settling
// or changing the route while the user's gesture is still active.
onPageChanged: (index) => _visibleIndex?.value = index,
children: [
for (final (index, child) in widget.children.indexed)
_KeepAlivePage(
@@ -0,0 +1,72 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/network/api_exception.dart';
import '../../device/data/device_providers.dart';
import '../../device/domain/device_models.dart';
// Keep this declaration explicit, as in device_providers.dart: the pinned
// Riverpod generator cannot parse the current Flutter SDK's dot shorthand.
final systemSettingsControllerProvider = NotifierProvider.autoDispose
.family<SystemSettingsController, AsyncValue<DevicePolicy?>, String>(
SystemSettingsController.new,
);
/// 页面级策略状态:先展示缓存,请求期间保留数据并锁定操作。
class SystemSettingsController
extends AutoDisposeFamilyNotifier<AsyncValue<DevicePolicy?>, String> {
late String _sn;
bool _active = true;
@override
AsyncValue<DevicePolicy?> build(String sn) {
_sn = sn;
_active = true;
ref.onDispose(() => _active = false);
unawaited(Future<void>.microtask(_load));
return const AsyncLoading();
}
Future<void> _load() async {
final repo = ref.read(deviceRepositoryProvider);
try {
final cached = await repo.getCachedPolicy(_sn);
if (!_active) return;
if (cached != null) {
state = const AsyncLoading<DevicePolicy?>().copyWithPrevious(
AsyncData(cached),
);
}
final policy = await repo.getPolicy(_sn);
if (_active) state = AsyncData(policy);
} catch (error, stack) {
if (_active) state = AsyncError(error, stack);
}
}
Future<void> toggle(String field, bool enabled) async {
if (state.isLoading || state.valueOrNull == null) return;
final previous = state;
state = const AsyncLoading<DevicePolicy?>().copyWithPrevious(previous);
try {
final repo = ref.read(deviceRepositoryProvider);
final error = await repo.togglePolicy(_sn, field, enabled ? 1 : 0);
if (!_active) return;
if (error != null) {
throw ApiException(code: 'policy_toggle', message: error);
}
final policy = await repo.getPolicy(_sn);
if (!_active) return;
state = AsyncData(policy);
ref.invalidate(devicePolicyProvider(_sn));
} catch (error, stack) {
if (_active) {
state = AsyncError<DevicePolicy?>(
error,
stack,
).copyWithPrevious(previous);
}
}
}
}
@@ -6,6 +6,8 @@ import 'package:ttstd_family_care/app/theme/dark_mode.dart';
import 'package:ttstd_family_care/core/widgets/app_page_scaffold.dart';
import '../../../core/widgets/feature_ui.dart';
import '../../../core/network/error_message.dart';
import 'system_settings_controller.dart';
import '../../../features/device/data/device_providers.dart';
import '../../../features/device/domain/device_models.dart';
import '../../../features/device/presentation/device_switcher.dart';
@@ -28,46 +30,67 @@ class SystemSettingsPage extends ConsumerWidget {
final sn = ref.watch(selectedDeviceSnProvider);
final policyAsync = sn == null
? const AsyncValue<DevicePolicy?>.data(null)
: ref.watch(devicePolicyProvider(sn));
: ref.watch(systemSettingsControllerProvider(sn));
final policy = policyAsync.valueOrNull;
final busy = policyAsync.isLoading;
if (sn != null) {
ref.listen(systemSettingsControllerProvider(sn), (previous, next) {
if (next.hasError && previous?.error != next.error) {
_showToast(context, userMessageOf(next.error!));
}
});
}
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) {
if (didPop) return;
if (didPop || busy) return;
if (context.canPop()) {
context.pop();
} else {
context.go('/home');
}
},
child: AppPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: DeviceContextTitle(l10n.ssTitle),
leading: CupertinoButton(
padding: EdgeInsets.zero,
child: const Icon(CupertinoIcons.back),
onPressed: () => context.pop(),
),
),
child: SafeArea(
child: policyAsync.when(
loading: () => const Center(child: CupertinoActivityIndicator()),
error: (e, _) => Center(
child: Text(l10n.commonLoadFailed,
style: TextStyle(color: DarkMode.color(context, AppColors.sub))),
child: Stack(
children: [
AppPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: DeviceContextTitle(l10n.ssTitle),
leading: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: busy ? null : () => context.pop(),
child: const Icon(CupertinoIcons.back),
),
),
child: SafeArea(
child: policy != null
? _buildGroups(context, ref, l10n, sn, policy)
: Center(
child: busy
? const SizedBox.shrink()
: Text(
l10n.ssLoadFailed,
style: TextStyle(
color: DarkMode.color(context, AppColors.sub),
),
),
),
),
data: (data) {
if (data == null) {
return Center(
child: Text(l10n.ssLoadFailed,
style: TextStyle(color: DarkMode.color(context, AppColors.sub))),
);
}
return _buildGroups(context, ref, l10n, sn, data);
},
),
),
if (busy) ...[
const Positioned.fill(
child: ModalBarrier(dismissible: false, color: Color(0x55000000)),
),
const Center(
child: CupertinoPopupSurface(
child: Padding(
padding: EdgeInsets.all(28),
child: CupertinoActivityIndicator(radius: 14),
),
),
),
],
],
),
);
}
@@ -181,54 +204,39 @@ class SystemSettingsPage extends ConsumerWidget {
Expanded(
child: Text(
item.label,
style: TextStyle(fontSize: 14.5, color: DarkMode.color(context, AppColors.ink)),
style: TextStyle(
fontSize: 14.5,
color: DarkMode.color(context, AppColors.ink),
),
),
),
CupertinoSwitch(
value: enabled,
activeColor: AppColors.green,
onChanged: (value) =>
_onToggle(context, ref, l10n, sn, item.field, value ? 1 : 0),
activeTrackColor: AppColors.green,
onChanged:
sn == null ||
ref.watch(systemSettingsControllerProvider(sn)).isLoading
? null
: (value) => ref
.read(systemSettingsControllerProvider(sn).notifier)
.toggle(item.field, value),
),
],
),
);
}
/// 调用 toggle 接口并刷新策略状态。
Future<void> _onToggle(
BuildContext context,
WidgetRef ref,
AppLocalizations l10n,
String? sn,
String field,
int value,
) async {
if (sn == null || sn.isEmpty) {
_showToast(context, l10n.opCmdFailed);
return;
}
final error = await ref
.read(deviceRepositoryProvider)
.togglePolicy(sn, field, value);
if (!context.mounted) return;
if (error == null) {
// 成功后仅刷新该策略数据,保证开关状态与后台一致。
ref.invalidate(devicePolicyProvider(sn));
} else {
_showToast(context, error);
}
}
/// 轻提示:以 SnackBar 展示结果,避免连续切换时被弹窗打断。
void _showToast(BuildContext context, String message) {
ScaffoldMessenger.of(context)
..clearSnackBars()
..showSnackBar(SnackBar(
content: Text(message),
duration: const Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
));
..showSnackBar(
SnackBar(
content: Text(message),
duration: const Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
),
);
}
}
@@ -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,