feat(client): 登录历史下拉、macOS 兼容修复、UI 优化

- 替换 flutter_secure_storage 为 shared_preferences,解决 macOS Keychain 签名报错
- 登录页门店编号/用户名支持历史下拉(最多5条,LRU 淘汰),使用 Overlay + CompositedTransformFollower 实现浮层
- logout 仅删除 auth token,保留登录历史
- AppShell 时钟抽为独立 _ClockWidget,避免每秒 setState 导致 TabBarView 叠影
- ShellRoute 子路由改用 NoTransitionPage,消除切换页面时的过渡动画叠影
- 新增 auth_state_test、auth_repository_test、login_screen_test 共 14 个单元/Widget 测试

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
wangjia
2026-04-05 01:21:40 +08:00
parent cc687ae0c3
commit 37112d6599
15 changed files with 895 additions and 407 deletions
+45 -38
View File
@@ -1,5 +1,5 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _kAccessToken = 'access_token';
const _kRefreshToken = 'refresh_token';
@@ -37,49 +37,54 @@ class AuthState {
}
class AuthNotifier extends StateNotifier<AuthState> {
final FlutterSecureStorage _storage;
AuthNotifier() : super(const AuthState());
AuthNotifier(this._storage) : super(const AuthState());
/// Called at app startup to restore persisted session
/// Called at app startup to restore persisted session.
Future<void> restore() async {
final accessToken = await _storage.read(key: _kAccessToken);
final refreshToken = await _storage.read(key: _kRefreshToken);
final username = await _storage.read(key: _kUsername);
final realName = await _storage.read(key: _kRealName);
final hotelNo = await _storage.read(key: _kHotelNo);
final hotelIdStr = await _storage.read(key: _kHotelId);
try {
final prefs = await SharedPreferences.getInstance();
final accessToken = prefs.getString(_kAccessToken);
final refreshToken = prefs.getString(_kRefreshToken);
final username = prefs.getString(_kUsername);
final realName = prefs.getString(_kRealName);
final hotelNo = prefs.getString(_kHotelNo);
final hotelIdStr = prefs.getString(_kHotelId);
if (accessToken != null && refreshToken != null && username != null) {
state = AuthState(
initialized: true,
user: AuthUser(
accessToken: accessToken,
refreshToken: refreshToken,
username: username,
realName: realName ?? username,
hotelNo: hotelNo ?? '',
hotelId: int.tryParse(hotelIdStr ?? '') ?? 0,
),
);
} else {
state = const AuthState(initialized: true);
if (accessToken != null && refreshToken != null && username != null) {
state = AuthState(
initialized: true,
user: AuthUser(
accessToken: accessToken,
refreshToken: refreshToken,
username: username,
realName: realName ?? username,
hotelNo: hotelNo ?? '',
hotelId: int.tryParse(hotelIdStr ?? '') ?? 0,
),
);
return;
}
} catch (_) {
// Storage unavailable — fall through to logged-out state
}
state = const AuthState(initialized: true);
}
Future<void> login(AuthUser user) async {
await _storage.write(key: _kAccessToken, value: user.accessToken);
await _storage.write(key: _kRefreshToken, value: user.refreshToken);
await _storage.write(key: _kUsername, value: user.username);
await _storage.write(key: _kRealName, value: user.realName);
await _storage.write(key: _kHotelNo, value: user.hotelNo);
await _storage.write(key: _kHotelId, value: user.hotelId.toString());
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_kAccessToken, user.accessToken);
await prefs.setString(_kRefreshToken, user.refreshToken);
await prefs.setString(_kUsername, user.username);
await prefs.setString(_kRealName, user.realName);
await prefs.setString(_kHotelNo, user.hotelNo);
await prefs.setString(_kHotelId, user.hotelId.toString());
state = AuthState(initialized: true, user: user);
}
void updateAccessToken(String newToken) {
if (state.user == null) return;
_storage.write(key: _kAccessToken, value: newToken);
SharedPreferences.getInstance()
.then((prefs) => prefs.setString(_kAccessToken, newToken));
state = AuthState(
initialized: true,
user: AuthUser(
@@ -94,15 +99,17 @@ class AuthNotifier extends StateNotifier<AuthState> {
}
Future<void> logout() async {
await _storage.deleteAll();
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_kAccessToken);
await prefs.remove(_kRefreshToken);
await prefs.remove(_kUsername);
await prefs.remove(_kRealName);
await prefs.remove(_kHotelNo);
await prefs.remove(_kHotelId);
state = const AuthState(initialized: true);
}
}
final _secureStorage = FlutterSecureStorage(
mOptions: MacOsOptions(groupId: 'com.jiu.client'),
);
final authStateProvider = StateNotifierProvider<AuthNotifier, AuthState>(
(ref) => AuthNotifier(_secureStorage),
(ref) => AuthNotifier(),
);
+19 -9
View File
@@ -1,3 +1,4 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../screens/auth/login_screen.dart';
@@ -13,6 +14,9 @@ import '../../screens/products/products_screen.dart';
import '../../screens/settings/settings_screen.dart';
import '../auth/auth_state.dart';
Page<void> _noTransition(Widget child) =>
NoTransitionPage<void>(child: child);
final appRouterProvider = Provider<GoRouter>((ref) {
final authState = ref.watch(authStateProvider);
@@ -35,27 +39,33 @@ final appRouterProvider = Provider<GoRouter>((ref) {
routes: [
GoRoute(
path: '/stock-in',
builder: (_, __) => const StockInListScreen()),
pageBuilder: (_, __) => _noTransition(const StockInListScreen())),
GoRoute(
path: '/stock-in/new',
builder: (_, __) => const StockInFormScreen()),
pageBuilder: (_, __) => _noTransition(const StockInFormScreen())),
GoRoute(
path: '/stock-out',
builder: (_, __) => const StockOutListScreen()),
pageBuilder: (_, __) => _noTransition(const StockOutListScreen())),
GoRoute(
path: '/inventory',
builder: (_, __) => const InventoryListScreen()),
pageBuilder: (_, __) =>
_noTransition(const InventoryListScreen())),
GoRoute(
path: '/inventory/check',
builder: (_, __) => const InventoryCheckScreen()),
pageBuilder: (_, __) =>
_noTransition(const InventoryCheckScreen())),
GoRoute(
path: '/partners', builder: (_, __) => const PartnersScreen()),
path: '/partners',
pageBuilder: (_, __) => _noTransition(const PartnersScreen())),
GoRoute(
path: '/finance', builder: (_, __) => const FinanceScreen()),
path: '/finance',
pageBuilder: (_, __) => _noTransition(const FinanceScreen())),
GoRoute(
path: '/products', builder: (_, __) => const ProductsScreen()),
path: '/products',
pageBuilder: (_, __) => _noTransition(const ProductsScreen())),
GoRoute(
path: '/settings', builder: (_, __) => const SettingsScreen()),
path: '/settings',
pageBuilder: (_, __) => _noTransition(const SettingsScreen())),
],
),
],
@@ -0,0 +1,36 @@
import 'package:shared_preferences/shared_preferences.dart';
/// Stores up to [_maxItems] recently used hotel codes and usernames.
/// List is ordered most-recent-first; least-recently-used entry is evicted
/// when the list exceeds the max.
class LoginHistoryStorage {
static const int _maxItems = 5;
static const String _hotelKey = 'login_history_hotels';
static const String _usernameKey = 'login_history_usernames';
static Future<List<String>> getHotelCodes() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getStringList(_hotelKey) ?? [];
}
static Future<List<String>> getUsernames() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getStringList(_usernameKey) ?? [];
}
/// Call after a successful login to persist both values.
static Future<void> record(String hotelCode, String username) async {
final prefs = await SharedPreferences.getInstance();
await _push(prefs, _hotelKey, hotelCode);
await _push(prefs, _usernameKey, username);
}
static Future<void> _push(
SharedPreferences prefs, String key, String value) async {
final list = prefs.getStringList(key) ?? [];
list.remove(value); // move to front if already present
list.insert(0, value);
if (list.length > _maxItems) list.removeLast();
await prefs.setStringList(key, list);
}
}
+355 -151
View File
@@ -3,6 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../core/auth/auth_state.dart';
import '../../core/theme/app_theme.dart';
import '../../core/storage/login_history.dart';
import '../../repositories/auth_repository.dart';
class LoginScreen extends ConsumerStatefulWidget {
@@ -17,15 +18,167 @@ class _LoginScreenState extends ConsumerState<LoginScreen> {
final _hotelCodeCtrl = TextEditingController();
final _usernameCtrl = TextEditingController();
final _passwordCtrl = TextEditingController();
final _hotelCodeFocus = FocusNode();
final _usernameFocus = FocusNode();
final _hotelLayerLink = LayerLink();
final _usernameLayerLink = LayerLink();
bool _loading = false;
bool _obscure = true;
String? _errorMessage;
List<String> _hotelCodeHistory = [];
List<String> _usernameHistory = [];
OverlayEntry? _hotelEntry;
OverlayEntry? _usernameEntry;
bool get _hotelShowing => _hotelEntry != null;
bool get _usernameShowing => _usernameEntry != null;
@override
void initState() {
super.initState();
_loadHistory();
_hotelCodeFocus.addListener(() {
if (_hotelCodeFocus.hasFocus && _hotelCodeHistory.isNotEmpty) {
_openDropdown(_hotelLayerLink, _hotelCodeHistory, _hotelCodeCtrl,
isHotel: true);
} else if (!_hotelCodeFocus.hasFocus) {
_closeHotel();
}
});
_usernameFocus.addListener(() {
if (_usernameFocus.hasFocus && _usernameHistory.isNotEmpty) {
_openDropdown(_usernameLayerLink, _usernameHistory, _usernameCtrl,
isHotel: false);
} else if (!_usernameFocus.hasFocus) {
_closeUsername();
}
});
}
Future<void> _loadHistory() async {
final hotels = await LoginHistoryStorage.getHotelCodes();
final users = await LoginHistoryStorage.getUsernames();
if (!mounted) return;
setState(() {
_hotelCodeHistory = hotels;
_usernameHistory = users;
});
// If a field is already focused, open its dropdown now that history loaded
if (_hotelCodeFocus.hasFocus && hotels.isNotEmpty) {
_openDropdown(_hotelLayerLink, hotels, _hotelCodeCtrl, isHotel: true);
}
if (_usernameFocus.hasFocus && users.isNotEmpty) {
_openDropdown(_usernameLayerLink, users, _usernameCtrl, isHotel: false);
}
}
void _openDropdown(
LayerLink link,
List<String> items,
TextEditingController ctrl, {
required bool isHotel,
}) {
if (isHotel) {
if (_hotelEntry != null) return;
_closeUsername();
} else {
if (_usernameEntry != null) return;
_closeHotel();
}
final entry = OverlayEntry(
builder: (_) => Stack(
children: [
// Transparent backdrop — tap outside closes dropdown
Positioned.fill(
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: isHotel ? _closeHotel : _closeUsername,
),
),
// Dropdown positioned below the field
CompositedTransformFollower(
link: link,
targetAnchor: Alignment.bottomLeft,
followerAnchor: Alignment.topLeft,
showWhenUnlinked: false,
child: Material(
elevation: 6,
borderRadius:
const BorderRadius.vertical(bottom: Radius.circular(4)),
child: SizedBox(
width: 320,
child: ListView.separated(
padding: EdgeInsets.zero,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: items.length,
separatorBuilder: (_, __) => const Divider(height: 1),
itemBuilder: (_, i) => GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (_) {
ctrl.text = items[i];
ctrl.selection = TextSelection.collapsed(
offset: items[i].length);
if (isHotel) { _closeHotel(); } else { _closeUsername(); }
},
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 10),
child: Row(
children: [
const Icon(Icons.history,
size: 14, color: AppTheme.textSecondary),
const SizedBox(width: 8),
Text(items[i],
style: const TextStyle(
fontSize: 14,
color: AppTheme.textPrimary)),
],
),
),
),
),
),
),
),
],
),
);
if (isHotel) {
_hotelEntry = entry;
} else {
_usernameEntry = entry;
}
Overlay.of(context).insert(entry);
setState(() {}); // refresh arrow icon
}
void _closeHotel() {
_hotelEntry?.remove();
_hotelEntry = null;
if (mounted) setState(() {});
}
void _closeUsername() {
_usernameEntry?.remove();
_usernameEntry = null;
if (mounted) setState(() {});
}
@override
void dispose() {
_hotelEntry?.remove();
_usernameEntry?.remove();
_hotelCodeCtrl.dispose();
_usernameCtrl.dispose();
_passwordCtrl.dispose();
_hotelCodeFocus.dispose();
_usernameFocus.dispose();
super.dispose();
}
@@ -35,13 +188,16 @@ class _LoginScreenState extends ConsumerState<LoginScreen> {
_loading = true;
_errorMessage = null;
});
try {
final user = await AuthRepository.login(
hotelCode: _hotelCodeCtrl.text.trim(),
username: _usernameCtrl.text.trim(),
password: _passwordCtrl.text,
);
await LoginHistoryStorage.record(
_hotelCodeCtrl.text.trim(),
_usernameCtrl.text.trim(),
);
await ref.read(authStateProvider.notifier).login(user);
if (mounted) context.go('/stock-in');
} on AuthException catch (e) {
@@ -59,170 +215,218 @@ class _LoginScreenState extends ConsumerState<LoginScreen> {
backgroundColor: AppTheme.primaryDark,
body: Stack(
children: [
// Background pattern
Positioned.fill(
child: CustomPaint(painter: _BackgroundPainter()),
),
Center(
child: Card(
elevation: 12,
shadowColor: Colors.black38,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
child: Container(
width: 400,
padding: const EdgeInsets.all(40),
child: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Logo
Container(
width: 80,
height: 80,
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [AppTheme.primaryLight, AppTheme.primaryDark],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: AppTheme.primary.withAlpha(102),
blurRadius: 12,
offset: const Offset(0, 4),
SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: MediaQuery.of(context).size.height,
),
child: Center(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 40),
child: Card(
elevation: 12,
shadowColor: Colors.black38,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
child: Container(
width: 400,
padding: const EdgeInsets.all(40),
child: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Logo
Container(
width: 80,
height: 80,
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [
AppTheme.primaryLight,
AppTheme.primaryDark
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: AppTheme.primary.withAlpha(102),
blurRadius: 12,
offset: const Offset(0, 4),
),
],
),
child: const Icon(Icons.wine_bar,
color: Colors.white, size: 44),
),
],
),
child: const Icon(Icons.wine_bar,
color: Colors.white, size: 44),
),
const SizedBox(height: 20),
const Text(
'酒库管理系统',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w700,
color: AppTheme.primaryDark,
letterSpacing: 1,
),
),
const SizedBox(height: 6),
const Text(
'酒店仓库管理解决方案',
style: TextStyle(
fontSize: 13, color: AppTheme.textSecondary),
),
const SizedBox(height: 32),
const SizedBox(height: 20),
const Text(
'酒库管理系统',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w700,
color: AppTheme.primaryDark,
letterSpacing: 1,
),
),
const SizedBox(height: 6),
const Text(
'酒店仓库管理解决方案',
style: TextStyle(
fontSize: 13,
color: AppTheme.textSecondary),
),
const SizedBox(height: 32),
// Hotel code
TextFormField(
controller: _hotelCodeCtrl,
decoration: const InputDecoration(
labelText: '门店编号',
hintText: '请输入门店编号',
prefixIcon: Icon(Icons.store_outlined, size: 20),
),
validator: (v) =>
(v == null || v.isEmpty) ? '请输入门店编号' : null,
textInputAction: TextInputAction.next,
),
const SizedBox(height: 14),
// Hotel code field
CompositedTransformTarget(
link: _hotelLayerLink,
child: TextFormField(
controller: _hotelCodeCtrl,
focusNode: _hotelCodeFocus,
decoration: InputDecoration(
labelText: '门店编号',
hintText: '请输入门店编号',
prefixIcon: const Icon(
Icons.store_outlined, size: 20),
suffixIcon: _hotelCodeHistory.isNotEmpty
? Icon(
_hotelShowing
? Icons.arrow_drop_up
: Icons.arrow_drop_down,
color: AppTheme.textSecondary,
)
: null,
),
validator: (v) =>
(v == null || v.isEmpty)
? '请输入门店编号'
: null,
textInputAction: TextInputAction.next,
),
),
const SizedBox(height: 14),
// Username
TextFormField(
controller: _usernameCtrl,
decoration: const InputDecoration(
labelText: '用户名',
hintText: '请输入用户名',
prefixIcon: Icon(Icons.person_outline, size: 20),
),
validator: (v) =>
(v == null || v.isEmpty) ? '请输入用户名' : null,
textInputAction: TextInputAction.next,
),
const SizedBox(height: 14),
// Username field
CompositedTransformTarget(
link: _usernameLayerLink,
child: TextFormField(
controller: _usernameCtrl,
focusNode: _usernameFocus,
decoration: InputDecoration(
labelText: '用户名',
hintText: '请输入用户名',
prefixIcon: const Icon(
Icons.person_outline, size: 20),
suffixIcon: _usernameHistory.isNotEmpty
? Icon(
_usernameShowing
? Icons.arrow_drop_up
: Icons.arrow_drop_down,
color: AppTheme.textSecondary,
)
: null,
),
validator: (v) =>
(v == null || v.isEmpty)
? '请输入用户名'
: null,
textInputAction: TextInputAction.next,
),
),
const SizedBox(height: 14),
// Password
TextFormField(
controller: _passwordCtrl,
obscureText: _obscure,
decoration: InputDecoration(
labelText: '密码',
hintText: '请输入密码',
prefixIcon:
const Icon(Icons.lock_outline, size: 20),
suffixIcon: IconButton(
icon: Icon(
_obscure
? Icons.visibility_off
: Icons.visibility,
size: 20),
onPressed: () =>
setState(() => _obscure = !_obscure),
),
),
validator: (v) =>
(v == null || v.isEmpty) ? '请输入密码' : null,
onFieldSubmitted: (_) => _login(),
),
// Password
TextFormField(
controller: _passwordCtrl,
obscureText: _obscure,
decoration: InputDecoration(
labelText: '密码',
hintText: '请输入密码',
prefixIcon: const Icon(Icons.lock_outline,
size: 20),
suffixIcon: IconButton(
icon: Icon(
_obscure
? Icons.visibility_off
: Icons.visibility,
size: 20),
onPressed: () =>
setState(() => _obscure = !_obscure),
),
),
validator: (v) =>
(v == null || v.isEmpty)
? '请输入密码'
: null,
onFieldSubmitted: (_) => _login(),
),
// Inline error message
if (_errorMessage != null) ...[
const SizedBox(height: 12),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: AppTheme.danger.withAlpha(15),
borderRadius: BorderRadius.circular(4),
border: Border.all(
color: AppTheme.danger.withAlpha(80)),
),
child: Row(
children: [
const Icon(Icons.error_outline,
color: AppTheme.danger, size: 16),
const SizedBox(width: 8),
Expanded(
child: Text(
_errorMessage!,
style: const TextStyle(
color: AppTheme.danger, fontSize: 13),
// Inline error
if (_errorMessage != null) ...[
const SizedBox(height: 12),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: AppTheme.danger.withAlpha(15),
borderRadius: BorderRadius.circular(4),
border: Border.all(
color: AppTheme.danger.withAlpha(80)),
),
child: Row(
children: [
const Icon(Icons.error_outline,
color: AppTheme.danger, size: 16),
const SizedBox(width: 8),
Expanded(
child: Text(
_errorMessage!,
style: const TextStyle(
color: AppTheme.danger,
fontSize: 13),
),
),
],
),
),
],
),
),
],
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
height: 46,
child: ElevatedButton(
onPressed: _loading ? null : _login,
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4)),
),
child: _loading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2, color: Colors.white))
: const Text('登 录',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
letterSpacing: 2)),
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
height: 46,
child: ElevatedButton(
onPressed: _loading ? null : _login,
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(4)),
),
child: _loading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white))
: const Text('登 录',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
letterSpacing: 2)),
),
),
],
),
),
],
),
),
),
),
+32 -23
View File
@@ -16,8 +16,6 @@ class AppShell extends ConsumerStatefulWidget {
class _AppShellState extends ConsumerState<AppShell> {
bool _sidebarExpanded = true;
late Timer _timer;
late String _currentTime;
final String _loginTime =
DateFormat('HH:mm:ss').format(DateTime.now());
@@ -34,24 +32,6 @@ class _AppShellState extends ConsumerState<AppShell> {
_NavItem(icon: Icons.settings, label: '系统设置', path: '/settings'),
];
@override
void initState() {
super.initState();
_currentTime = DateFormat('HH:mm:ss').format(DateTime.now());
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted) {
setState(() =>
_currentTime = DateFormat('HH:mm:ss').format(DateTime.now()));
}
});
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final user = ref.watch(authStateProvider).user;
@@ -192,9 +172,7 @@ class _AppShellState extends ConsumerState<AppShell> {
text: '登录时间:$_loginTime'),
const _StatusDivider(),
],
_StatusItem(
icon: Icons.access_time,
text: '当前时间:$_currentTime'),
const _ClockWidget(),
const Spacer(),
const _StatusItem(
icon: Icons.info_outline,
@@ -325,3 +303,34 @@ class _StatusDivider extends StatelessWidget {
);
}
}
class _ClockWidget extends StatefulWidget {
const _ClockWidget();
@override
State<_ClockWidget> createState() => _ClockWidgetState();
}
class _ClockWidgetState extends State<_ClockWidget> {
late Timer _timer;
late String _time;
@override
void initState() {
super.initState();
_time = DateFormat('HH:mm:ss').format(DateTime.now());
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted) setState(() => _time = DateFormat('HH:mm:ss').format(DateTime.now()));
});
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return _StatusItem(icon: Icons.access_time, text: '当前时间:$_time');
}
}