Flutter商城登录界面实现:API调用、Cookie管理与跳转
好的,我可以为您编写一个基本的登录界面和相应的代码。
首先,您需要创建一个新的 Dart 文件来放置登录界面的代码。我们将使用StatefulWidget来创建该界面,以便可以在输入表单中保存用户输入的值。
import 'package:flutter/material.dart';
class LoginPage extends StatefulWidget {
const LoginPage({Key? key}) : super(key: key);
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final _formKey = GlobalKey<FormState>();
String _email = '';
String _password = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
decoration: const InputDecoration(
hintText: 'Enter your email',
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
}
return null;
},
onChanged: (value) {
setState(() {
_email = value;
});
},
),
TextFormField(
decoration: const InputDecoration(
hintText: 'Enter your password',
),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
}
return null;
},
onChanged: (value) {
setState(() {
_password = value;
});
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// TODO: Call login API and check response
}
},
child: Text('Login'),
),
),
],
),
),
),
);
}
}
上述代码创建了一个带有表单的界面,其中包含一个用于输入电子邮件地址的文本字段和一个用于输入密码的文本字段。当用户在这些字段中输入信息时,onChanged回调将更新相应的私有变量。在用户尝试提交表单时,validator回调将检查这些字段是否为空,并显示适当的错误消息。
现在,我们需要为登录API创建一个新的方法。我将使用Dio库来发出HTTP请求并解析响应。在这个方法中,我们将使用name和password参数来构建API的URL,并发送POST请求。如果响应状态码为200,则表示登录成功,并且我们可以从响应头中提取cookie。
import 'dart:convert';
import 'package:dio/dio.dart';
class ApiService {
static final String baseUrl = "http://book.musecloud.tech";
static Dio _dio = Dio();
static Future<bool> login(String email, String password) async {
try {
Response response = await _dio.post(
'$baseUrl/user/login',
queryParameters: {
'name': email,
'password': password,
},
);
if (response.statusCode == 200) {
String? cookie = response.headers.value('set-cookie');
// TODO: Save cookie to local storage
return true;
} else {
return false;
}
} catch (e) {
throw e;
}
}
}
现在,我们可以在我们的登录页面中调用login方法,以在用户提交表单时尝试登录。如果登录成功,则我们可以将cookie保存到本地存储中,并将用户重定向到我们的主页。
import 'package:flutter/material.dart';
import 'package:my_app/api/api_service.dart';
class LoginPage extends StatefulWidget {
const LoginPage({Key? key}) : super(key: key);
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final _formKey = GlobalKey<FormState>();
String _email = '';
String _password = '';
Future<void> _login() async {
bool success = await ApiService.login(_email, _password);
if (success) {
// TODO: Navigate to homepage
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Invalid email or password'),
),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
decoration: const InputDecoration(
hintText: 'Enter your email',
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
}
return null;
},
onChanged: (value) {
setState(() {
_email = value;
});
},
),
TextFormField(
decoration: const InputDecoration(
hintText: 'Enter your password',
),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
}
return null;
},
onChanged: (value) {
setState(() {
_password = value;
});
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
_login();
}
},
child: Text('Login'),
),
),
],
),
),
),
);
}
}
上述代码中,我们创建了一个新的_login方法,该方法调用ApiService.login方法来尝试登录用户。如果登录成功,则我们将导航到主页。如果登录失败,则我们将显示一个SnackBar来告诉用户他们的凭据无效。
希望这有助于您编写您的登录界面和相应的API服务。如果您有任何问题或需要进一步的帮助,请告诉我。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/oibe 著作权归作者所有。请勿转载和采集!