用flutter写一个精美的登陆页面 要求请求接口 请求成功跳转页面失败返回错误信息 实现代码
时间: 2024-05-23 11:15:06 浏览: 140
很高兴回答您的问题!以下是实现该功能的Flutter代码示例:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
bool _isLoading = false;
Future<void> _login() async {
setState(() {
_isLoading = true;
});
final String apiUrl = 'https://example.com/login'; // 接口请求链接
final Map<String, dynamic> userData = {
'email': _emailController.text.trim(),
'password': _passwordController.text.trim(),
};
final http.Response response = await http.post(
apiUrl,
body: userData,
);
setState(() {
_isLoading = false;
});
if (response.statusCode == 200) { // 请求成功,跳转页面
Navigator.pushReplacementNamed(context, '/home');
} else { // 请求失败,返回错误信息
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content: Text(response.body),
actions: <Widget>[
FlatButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Login'),
),
body: SingleChildScrollView(
child: Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
labelText: 'Email',
hintText: 'Enter your email',
),
validator: (String value) {
if (value.isEmpty) {
return 'Please enter your email';
}
return null;
},
),
const SizedBox(height: 16.0),
TextFormField(
controller: _passwordController,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Password',
hintText: 'Enter your password',
),
validator: (String value) {
if (value.isEmpty) {
return 'Please enter your password';
}
return null;
},
),
const SizedBox(height: 16.0),
_isLoading
? const CircularProgressIndicator()
: RaisedButton(
child: const Text('Login'),
onPressed: () {
if (_formKey.currentState.validate()) {
_login();
}
},
),
],
),
),
),
),
);
}
}
需要注意的是,该示例仅仅是一种实现方式,实际上实现一个精美的登录页面还需要在视觉和交互等方面进行优化。同时,接口请求的方式也需要根据具体的实际需求进行调整。
阅读全文