100 lines
2.4 KiB
Dart
100 lines
2.4 KiB
Dart
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);
|
|
|
|
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 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,
|
|
);
|
|
}
|
|
}
|