login.dart 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import 'package:chicken_farm/core/utils/logger.dart';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_riverpod/flutter_riverpod.dart';
  4. import 'package:go_router/go_router.dart';
  5. import 'package:chicken_farm/core/utils/toast.dart';
  6. import 'package:chicken_farm/modes/auth/login_model.dart';
  7. import 'package:chicken_farm/routes/app_routes.dart';
  8. import 'package:chicken_farm/stores/auth_store.dart';
  9. import 'package:chicken_farm/widgets/config_dialog.dart';
  10. class LoginPage extends ConsumerStatefulWidget {
  11. const LoginPage({super.key});
  12. @override
  13. ConsumerState<LoginPage> createState() => _LoginPageState();
  14. }
  15. class _LoginPageState extends ConsumerState<LoginPage> {
  16. final _formKey = GlobalKey<FormState>();
  17. final _usernameCtrl = TextEditingController(text: 'admin');
  18. final _passwordCtrl = TextEditingController(text: '123iwb');
  19. @override
  20. void dispose() {
  21. _usernameCtrl.dispose();
  22. _passwordCtrl.dispose();
  23. super.dispose();
  24. }
  25. @override
  26. Widget build(BuildContext context) {
  27. final authState = ref.watch(authStoreProvider);
  28. final authStore = ref.read(authStoreProvider.notifier);
  29. // 监听认证状态变化,如果已认证则跳转到主页
  30. WidgetsBinding.instance.addPostFrameCallback((_) {
  31. if (authState.state == AuthState.authenticated && context.mounted) {
  32. context.goNamed(AppRoutePaths.home);
  33. }
  34. });
  35. ref.listen<AuthInfo>(authStoreProvider, (previous, next) {
  36. if (next.state == AuthState.authenticated) {
  37. // 登录成功,跳转到主页
  38. if (context.mounted) {
  39. context.goNamed(AppRoutePaths.home);
  40. }
  41. }
  42. });
  43. return Scaffold(
  44. appBar: AppBar(
  45. title: const Text('用户登录'),
  46. backgroundColor: Theme.of(context).colorScheme.primary,
  47. foregroundColor: Colors.white,
  48. ),
  49. body: Stack(
  50. children: [
  51. Container(
  52. decoration: BoxDecoration(
  53. gradient: LinearGradient(
  54. begin: Alignment.topCenter,
  55. end: Alignment.bottomCenter,
  56. colors: [
  57. Theme.of(context).colorScheme.primary.withValues(alpha: 0.1),
  58. Theme.of(context).colorScheme.surface,
  59. ],
  60. ),
  61. ),
  62. child: Center(
  63. child: SingleChildScrollView(
  64. padding: const EdgeInsets.all(24.0),
  65. child: Card(
  66. elevation: 8,
  67. shape: RoundedRectangleBorder(
  68. borderRadius: BorderRadius.circular(16),
  69. ),
  70. child: Padding(
  71. padding: const EdgeInsets.all(24.0),
  72. child: Form(
  73. key: _formKey,
  74. child: Column(
  75. mainAxisSize: MainAxisSize.min,
  76. children: [
  77. Text(
  78. '养殖场管理系统',
  79. style: TextStyle(
  80. fontSize: 24,
  81. fontWeight: FontWeight.bold,
  82. color: Theme.of(context).colorScheme.primary,
  83. ),
  84. ),
  85. const SizedBox(height: 24),
  86. TextFormField(
  87. controller: _usernameCtrl,
  88. decoration: InputDecoration(
  89. labelText: '用户名',
  90. prefixIcon: const Icon(Icons.person),
  91. border: OutlineInputBorder(
  92. borderRadius: BorderRadius.circular(12),
  93. ),
  94. filled: true,
  95. fillColor: Colors.grey[50],
  96. ),
  97. validator: (v) => v!.isEmpty ? '请输入用户名' : null,
  98. ),
  99. const SizedBox(height: 16),
  100. TextFormField(
  101. controller: _passwordCtrl,
  102. obscureText: true,
  103. decoration: InputDecoration(
  104. labelText: '密码',
  105. prefixIcon: const Icon(Icons.lock),
  106. border: OutlineInputBorder(
  107. borderRadius: BorderRadius.circular(12),
  108. ),
  109. filled: true,
  110. fillColor: Colors.grey[50],
  111. ),
  112. validator: (v) => v!.length < 6 ? '密码不能少于6位' : null,
  113. ),
  114. const SizedBox(height: 24),
  115. SizedBox(
  116. width: double.infinity,
  117. height: 50,
  118. child: ElevatedButton(
  119. onPressed: authState.state == AuthState.loading
  120. ? null
  121. : () {
  122. if (_formKey.currentState!.validate()) {
  123. authStore
  124. .login(
  125. LoginModel(
  126. username: _usernameCtrl.text,
  127. password: _passwordCtrl.text,
  128. ),
  129. )
  130. .then((_) async {
  131. // 登录成功后跳转到主页
  132. if (context.mounted) {
  133. logger.d('登录成功');
  134. context.goNamed(
  135. AppRoutePaths.home,
  136. );
  137. }
  138. })
  139. .catchError((error) {
  140. // 处理登录错误
  141. logger.e('登录失败: $error');
  142. if (context.mounted) {
  143. String errorMessage = '登录失败';
  144. if (error is Exception) {
  145. errorMessage = error.toString();
  146. }
  147. ToastUtils.error(errorMessage);
  148. }
  149. });
  150. }
  151. },
  152. style: ElevatedButton.styleFrom(
  153. shape: RoundedRectangleBorder(
  154. borderRadius: BorderRadius.circular(12),
  155. ),
  156. textStyle: const TextStyle(fontSize: 16),
  157. ),
  158. child: authState.state == AuthState.loading
  159. ? const CircularProgressIndicator(
  160. color: Colors.white,
  161. )
  162. : const Text('登录'),
  163. ),
  164. ),
  165. ],
  166. ),
  167. ),
  168. ),
  169. ),
  170. ),
  171. ),
  172. ),
  173. Positioned(
  174. bottom: 16,
  175. right: 16,
  176. child: IconButton(
  177. icon: const Icon(Icons.settings),
  178. onPressed: () async {
  179. final result = await showDialog(
  180. context: context,
  181. builder: (context) => const ConfigDialog(),
  182. );
  183. // 如果配置发生了变化,显示提示
  184. if (result == true && context.mounted) {
  185. // ScaffoldMessenger.of(context).showSnackBar(
  186. // const SnackBar(
  187. // content: Text('配置已保存'),
  188. // duration: Duration(seconds: 2),
  189. // ),
  190. // );
  191. ToastUtils.success('配置已保存');
  192. }
  193. },
  194. ),
  195. ),
  196. ],
  197. ),
  198. );
  199. }
  200. }