129 lines
3.6 KiB
Dart
129 lines
3.6 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:dio/dio.dart';
|
|
|
|
class LoginPage extends StatefulWidget {
|
|
const LoginPage({super.key});
|
|
|
|
@override
|
|
State<LoginPage> createState() => _LoginPageState();
|
|
}
|
|
|
|
class _LoginPageState extends State<LoginPage> {
|
|
final _formKey = GlobalKey<FormState>();
|
|
final _usernameController = TextEditingController();
|
|
final _passwordController = TextEditingController();
|
|
bool _isLoading = false;
|
|
final _dio = Dio();
|
|
|
|
Future<void> _submitForm() async {
|
|
if (_formKey.currentState!.validate()) {
|
|
setState(() {
|
|
_isLoading = true;
|
|
});
|
|
|
|
try {
|
|
final response = await _dio.post(
|
|
'https://api.fishestlife.com/user/login',
|
|
data: {
|
|
'username': _usernameController.text.trim(),
|
|
'password': _passwordController.text.trim(),
|
|
},
|
|
);
|
|
|
|
// 登录成功处理
|
|
if (response.statusCode == 200) {
|
|
// 这里根据实际返回的数据结构处理
|
|
if (mounted) {
|
|
ScaffoldMessenger.of(
|
|
context,
|
|
).showSnackBar(const SnackBar(content: Text('登录成功')));
|
|
// 导航到主页或其他页面
|
|
// Navigator.pushReplacement(...);
|
|
}
|
|
}
|
|
} catch (e) {
|
|
// 错误处理
|
|
if (mounted) {
|
|
ScaffoldMessenger.of(
|
|
context,
|
|
).showSnackBar(SnackBar(content: Text('登录失败: ${e.toString()}')));
|
|
}
|
|
} finally {
|
|
if (mounted) {
|
|
setState(() {
|
|
_isLoading = false;
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: AppBar(title: const Text('登录')),
|
|
body: Padding(
|
|
padding: const EdgeInsets.all(16.0),
|
|
child: Form(
|
|
key: _formKey,
|
|
child: Column(
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
children: [
|
|
TextFormField(
|
|
controller: _usernameController,
|
|
decoration: const InputDecoration(
|
|
labelText: '用户名',
|
|
prefixIcon: Icon(Icons.person),
|
|
border: OutlineInputBorder(),
|
|
),
|
|
validator: (value) {
|
|
if (value == null || value.isEmpty) {
|
|
return '请输入用户名';
|
|
}
|
|
return null;
|
|
},
|
|
enabled: !_isLoading,
|
|
),
|
|
const SizedBox(height: 16),
|
|
TextFormField(
|
|
controller: _passwordController,
|
|
decoration: const InputDecoration(
|
|
labelText: '密码',
|
|
prefixIcon: Icon(Icons.lock),
|
|
border: OutlineInputBorder(),
|
|
),
|
|
obscureText: true,
|
|
validator: (value) {
|
|
if (value == null || value.isEmpty) {
|
|
return '请输入密码';
|
|
}
|
|
return null;
|
|
},
|
|
enabled: !_isLoading,
|
|
),
|
|
const SizedBox(height: 24),
|
|
SizedBox(
|
|
width: double.infinity,
|
|
child: ElevatedButton(
|
|
onPressed: _isLoading ? null : _submitForm,
|
|
child: _isLoading
|
|
? const CircularProgressIndicator()
|
|
: const Text('登录'),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_usernameController.dispose();
|
|
_passwordController.dispose();
|
|
_dio.close();
|
|
super.dispose();
|
|
}
|
|
}
|