petsHero-AI/lib/core/user/user_state.dart
2026-03-12 14:30:19 +08:00

107 lines
2.7 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:flutter/material.dart';
/// 用户积分等全局状态
class UserState {
UserState._();
static final ValueNotifier<int?> credits = ValueNotifier<int?>(null);
static final ValueNotifier<String?> userId = ValueNotifier<String?>(null);
static final ValueNotifier<String?> avatar = ValueNotifier<String?>(null);
static final ValueNotifier<String?> userName = ValueNotifier<String?>(null);
/// 国家码 (navigate / countryCode)
static final ValueNotifier<String?> navigate = ValueNotifier<String?>(null);
/// 是否启用第三方支付(来自 common_info surge.enable_third_party_payment
static final ValueNotifier<bool?> enableThirdPartyPayment =
ValueNotifier<bool?>(null);
static void setCredits(int? value) {
credits.value = value;
}
static void setUserId(String? value) {
userId.value = value;
}
static void setAvatar(String? value) {
avatar.value = value;
}
static void setUserName(String? value) {
userName.value = value;
}
static void setNavigate(String? value) {
navigate.value = value;
}
static void setEnableThirdPartyPayment(bool? value) {
enableThirdPartyPayment.value = value;
}
static String formatCredits(int? value) {
if (value == null) return '--';
return value.toString().replaceAllMapped(
RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
(m) => '${m[1]},',
);
}
}
/// 提供积分数据的 InheritedWidget
class UserCreditsData extends InheritedWidget {
const UserCreditsData({
super.key,
required this.credits,
required super.child,
});
final int? credits;
static UserCreditsData? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<UserCreditsData>();
}
String get creditsDisplay => UserState.formatCredits(credits);
@override
bool updateShouldNotify(UserCreditsData oldWidget) {
return oldWidget.credits != credits;
}
}
/// 监听 UserState.credits 并向下提供 UserCreditsData
class UserCreditsScope extends StatefulWidget {
const UserCreditsScope({super.key, required this.child});
final Widget child;
@override
State<UserCreditsScope> createState() => _UserCreditsScopeState();
}
class _UserCreditsScopeState extends State<UserCreditsScope> {
@override
void initState() {
super.initState();
UserState.credits.addListener(_onCreditsChanged);
}
@override
void dispose() {
UserState.credits.removeListener(_onCreditsChanged);
super.dispose();
}
void _onCreditsChanged() {
setState(() {});
}
@override
Widget build(BuildContext context) {
return UserCreditsData(
credits: UserState.credits.value,
child: widget.child,
);
}
}