login.dart 8.7 KB

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