登录流程已全部重构

This commit is contained in:
zhutao
2025-09-23 11:47:29 +08:00
parent a4992a063b
commit 8988b3feea
71 changed files with 2036 additions and 901 deletions

View File

@@ -0,0 +1,23 @@
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class AgreePage extends StatelessWidget {
final String title;
final String url;
const AgreePage({super.key, required this.title, required this.url});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: WebViewWidget(
controller: WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..loadRequest(Uri.parse(url)),
),
);
}
}

View File

@@ -0,0 +1,223 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:food_health/api/endpoints/user_api.dart';
import 'package:food_health/api/network/safe.dart';
import 'package:food_health/l10n/l10n.dart';
import 'package:food_health/router/config/route_paths.dart';
import 'package:food_health/stores/app_store.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
class LoginCodePage extends StatefulWidget {
final String email;
final String password;
const LoginCodePage({super.key, required this.email, required this.password});
@override
State<LoginCodePage> createState() => _LoginCodePageState();
}
class _LoginCodePageState extends State<LoginCodePage> {
final List<FocusNode> _focusNodes = List.generate(4, (_) => FocusNode());
final List<TextEditingController> _controllers = List.generate(
4,
(_) => TextEditingController(),
);
//倒计时
int _count = 60;
Timer? _timer;
@override
void initState() {
super.initState();
_handSendCode();
}
@override
void dispose() {
_timer?.cancel();
_handClear();
super.dispose();
}
///小输入框改变时
void _onChanged(String value, int index) async {
//一键复制
if (value.length == 4) {
_handlePaste(value);
}
//提交
if (value.isNotEmpty && index == 3) {
_handSubmit();
return;
}
// 自动跳到下一格
if (value.length == 1 && index < 3) {
_focusNodes[index + 1].requestFocus();
}
}
void _handlePaste(String pastedText) {
// 只取前4位数字
final digits = pastedText.replaceAll(RegExp(r'[^0-9]'), '');
for (int i = 0; i < 4; i++) {
_controllers[i].text = i < digits.length ? digits[i] : '';
}
if (digits.length >= 4) {
_focusNodes[3].requestFocus();
_handSubmit();
} else if (digits.isNotEmpty) {
_focusNodes[digits.length].requestFocus();
}
}
///删除键
void _onDelete(KeyEvent event, int index) {
if (event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.backspace) {
final currentController = _controllers[index];
if (currentController.text.isEmpty && index > 0) {
_focusNodes[index - 1].requestFocus();
_controllers[index - 1].clear();
}
}
}
///发送验证码
void _handSendCode() {
if (_count != 60) {
return;
}
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
_count--;
});
if (_count == 0) {
setState(() {
_count = 60;
});
timer.cancel();
}
});
sendEmailCodeApi(widget.email);
EasyLoading.showToast(L10n.of.code_success);
}
///提交
void _handSubmit() async {
String code = _controllers.map((controller) => controller.text).join();
if (code.length == 4) {
EasyLoading.show();
var res = await safeRequest(
registerApi(
widget.email,
widget.password,
code,
),
onError: (error) {
_handClear();
EasyLoading.showToast(L10n.of.code_error);
},
);
var appStore = context.read<AppStore>();
await appStore.setInfo(res);
context.go(RoutePaths.layout);
}
}
///清空
void _handClear() {
for (var controller in _controllers) {
controller.clear();
}
_focusNodes.first.requestFocus();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ListView(
physics: NeverScrollableScrollPhysics(),
padding: EdgeInsets.all(20),
children: [
Container(
margin: EdgeInsets.only(bottom: 20),
child: Text(L10n.of.code_title, style: Theme.of(context).textTheme.titleLarge),
),
Container(
margin: EdgeInsets.only(bottom: 60),
child: Text(
"${L10n.of.code_tip} ${widget.email}",
style: Theme.of(context).textTheme.labelLarge,
),
),
Row(
spacing: 20,
children: List.generate(4, (index) {
return Expanded(
child: AspectRatio(
aspectRatio: 1,
child: Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainer,
borderRadius: BorderRadius.circular(10),
),
child: KeyboardListener(
focusNode: FocusNode(),
onKeyEvent: (event) {
_onDelete(event, index);
},
child: TextField(
controller: _controllers[index],
focusNode: _focusNodes[index],
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
maxLength: 4,
style: TextStyle(fontSize: 32),
decoration: InputDecoration(
counterText: "",
border: InputBorder.none,
isCollapsed: true,
),
onChanged: (value) {
_onChanged(value, index);
},
),
),
),
),
);
}),
),
Container(
margin: EdgeInsets.only(top: 30),
child: Row(
children: [
GestureDetector(
onTap: _handSendCode,
child: Visibility(
visible: _count != 60,
replacement: Text(
L10n.of.code_send_code,
style: Theme.of(context).textTheme.bodySmall,
),
child: Text(
"${L10n.of.code_send_code}${_count}s",
style: Theme.of(context).textTheme.labelLarge,
),
),
),
],
),
),
],
),
);
}
}

View File

@@ -0,0 +1,69 @@
import 'package:flutter/material.dart';
import 'package:food_health/l10n/l10n.dart';
import 'package:food_health/router/config/route_paths.dart';
import 'package:food_health/widgets/ui_kit/button/app_button.dart';
import 'package:go_router/go_router.dart';
class IntroPage extends StatefulWidget {
const IntroPage({super.key});
@override
State<IntroPage> createState() => _IntroPageState();
}
class _IntroPageState extends State<IntroPage> {
void _onTap() {
context.go(RoutePaths.login);
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.white,
body: SafeArea(
child: SizedBox(
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
padding: EdgeInsets.all(50),
child: Image.asset("assets/image/bg/intro_bg.png"),
),
Expanded(
child: Padding(
padding: EdgeInsets.all(20),
child: Column(
children: [
Container(
margin: EdgeInsets.only(bottom: 20),
child: Text(
L10n.of.welcome_title,
style: Theme.of(context).textTheme.titleMedium,
),
),
Text(
L10n.of.welcome_desc,
style: Theme.of(context).textTheme.labelMedium,
),
Container(
height: 50,
margin: EdgeInsets.only(top: 20),
child: AppButton(
onPressed: _onTap,
child: Text(L10n.of.welcome_button_text),
),
),
],
),
),
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,289 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:food_health/api/endpoints/user_api.dart';
import 'package:food_health/data/models/other_login_type.dart';
import 'package:food_health/l10n/l10n.dart';
import 'package:food_health/pages/system/login/widgets/login_input.dart';
import 'package:food_health/router/config/route_paths.dart';
import 'package:food_health/stores/app_store.dart';
import 'package:food_health/widgets/ui_kit/button/app_button.dart';
import 'package:go_router/go_router.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:provider/provider.dart';
import 'package:remixicon/remixicon.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import '../../../utils/common.dart';
import 'widgets/login_agree.dart';
import 'widgets/login_other.dart';
import 'package:logger/logger.dart';
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
Logger logger = Logger();
var _subLoading = false;
///邮箱输入框
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
//显示密码
bool _hidePassword = true;
///谷歌登陆
final GoogleSignIn _googleSignIn = GoogleSignIn.instance;
@override
void initState() {
super.initState();
_emailController.addListener(() {
setState(() {});
});
_passwordController.addListener(() {
setState(() {});
});
_ensureNetworkPermission();
_initGoogleSign();
}
/// 预触发 iOS 网络权限弹窗
Future<bool> _ensureNetworkPermission() async {
try {
await Dio().get(
'https://captive.apple.com/hotspot-detect.html',
options: Options(
sendTimeout: const Duration(seconds: 3),
receiveTimeout: const Duration(seconds: 3),
headers: {'Cache-Control': 'no-cache'},
),
);
return true;
} catch (_) {
return false;
}
}
void _initGoogleSign() {
if (isAndroid()) {
_googleSignIn.initialize(
clientId: null,
serverClientId:
"512878764950-0bsl98c4q4p695mlmfn35qhmr2ld5n0o.apps.googleusercontent.com",
);
} else {
_googleSignIn.initialize(
clientId: "512878764950-1ke7slf0c6dlmchnuk0fqh3fe954gcf2.apps.googleusercontent.com",
serverClientId:
"512878764950-0bsl98c4q4p695mlmfn35qhmr2ld5n0o.apps.googleusercontent.com",
);
}
_googleSignIn.authenticationEvents
.listen((_) {
logger.d("登陆成功");
})
.onError((error) {
logger.e("登陆错误: $error");
});
}
///谷歌登录
void _handGoogleSignIn() async {
try {
// 如果用户未登录,则启动标准的 Google 登录
if (_googleSignIn.supportsAuthenticate()) {
// 使用 authenticate() 进行认证
GoogleSignInAccount? user = await _googleSignIn.authenticate();
var auth = user.authentication;
//登陆
EasyLoading.show();
var res = await thirdLoginApi(auth.idToken!, OtherLoginType.google);
EasyLoading.dismiss();
_onLogin(res);
}
} catch (e) {
EasyLoading.showError(L10n.of.login_error_text);
logger.e("登录错误: $e");
}
}
///apple登录
void _handAppleSignIn() async {
try {
final credential = await SignInWithApple.getAppleIDCredential(
scopes: [
AppleIDAuthorizationScopes.email,
AppleIDAuthorizationScopes.fullName,
],
);
EasyLoading.show();
var res = await thirdLoginApi(credential.identityToken!, OtherLoginType.apple);
EasyLoading.dismiss();
_onLogin(res);
logger.d('Apple Credential: ${credential.identityToken}');
logger.d('Apple Email: ${credential.email}');
} catch (e) {
logger.e("登录错误: $e");
}
}
void _handSubmit() async {
if (_emailController.text.isEmpty) {
//请输入邮箱
EasyLoading.showToast(L10n.of.login_email_hint);
return;
} else if (_passwordController.text.isEmpty) {
EasyLoading.showToast(L10n.of.login_password_hint);
return;
}
try {
setState(() {
_subLoading = true;
});
var isRegister = await checkRegisterApi(_emailController.text);
if (!isRegister && mounted) {
context.push(
RoutePaths.loginCode,
extra: {
"email": _emailController.text,
"password": _passwordController.text,
},
);
} else {
var res = await loginApi(_emailController.text, _passwordController.text);
_onLogin(res);
}
setState(() {
_subLoading = false;
});
} catch (e) {
setState(() {
_subLoading = false;
});
}
}
///登陆的操作
void _onLogin(dynamic res) {
var appStore = context.read<AppStore>();
appStore.setInfo(res);
context.go(RoutePaths.layout);
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: SafeArea(
child: Container(
padding: EdgeInsets.only(
left: 20,
right: 20,
top: 0.08.sh,
bottom: 40,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: EdgeInsets.only(bottom: 40),
child: Text(
L10n.of.login_title,
style: Theme.of(context).textTheme.titleLarge,
),
),
LoginInput(
hintText: L10n.of.login_email_hint,
controller: _emailController,
suffix: Visibility(
visible: _emailController.text.isNotEmpty,
child: InkWell(
onTap: () {
_emailController.clear();
},
child: Icon(
RemixIcons.close_circle_fill,
size: 20,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
),
SizedBox(height: 20),
LoginInput(
hintText: L10n.of.login_password_hint,
controller: _passwordController,
obscureText: _hidePassword,
suffix: InkWell(
onTap: () {
setState(() {
_hidePassword = !_hidePassword;
});
},
child: Icon(
_hidePassword ? RemixIcons.eye_off_fill : RemixIcons.eye_fill,
size: 20,
),
),
),
Container(
margin: EdgeInsets.only(top: 40),
height: 50,
child: AppButton(
disabled: _emailController.text.isEmpty || _passwordController.text.isEmpty,
loading: _subLoading,
onPressed: _handSubmit,
child: Text(L10n.of.login_button),
),
),
Container(
width: double.infinity,
margin: EdgeInsets.only(top: 20),
alignment: Alignment.center,
child: LoginAgree(),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
LoginDivider(),
Row(
spacing: 20,
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
OtherButton(
onTap: () {
_handGoogleSignIn();
},
icon: "assets/image/google.png",
),
OtherButton(
onTap: () {
_handAppleSignIn();
},
icon: "assets/image/apple.png",
),
],
),
],
),
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,50 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:food_health/l10n/l10n.dart';
import 'package:food_health/router/config/route_paths.dart';
import 'package:go_router/go_router.dart';
class LoginAgree extends StatelessWidget {
const LoginAgree({
super.key,
});
@override
Widget build(BuildContext context) {
return RichText(
text: TextSpan(
style: Theme.of(context).textTheme.labelMedium,
children: [
TextSpan(
text: "${L10n.of.login_tip_start} ",
),
TextSpan(
text: L10n.of.login_terms,
style: TextStyle(color: Theme.of(context).primaryColor),
recognizer: TapGestureRecognizer()
..onTap = () => context.push(
RoutePaths.agreement,
extra: {
"title": "Terms of Service",
"url": "https://support.curain.ai/privacy/foodcura/terms_service.html",
},
),
),
TextSpan(text: " ${L10n.of.login_and} "),
TextSpan(
text: L10n.of.login_privacy,
style: TextStyle(color: Theme.of(context).primaryColor),
recognizer: TapGestureRecognizer()
..onTap = () => context.push(
RoutePaths.agreement,
extra: {
"title": "Privacy",
"url": "https://support.curain.ai/privacy/foodcura/privacy_policy.html",
},
),
),
],
),
);
}
}

View File

@@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
class LoginInput extends StatelessWidget {
final bool obscureText;
final String hintText;
final TextEditingController controller;
final Widget? suffix;
const LoginInput({
super.key,
this.obscureText = false,
required this.hintText,
required this.controller,
this.suffix,
});
@override
Widget build(BuildContext context) {
return TextField(
controller: controller,
obscureText: obscureText,
maxLength: 100,
decoration: InputDecoration(
hintText: hintText,
hintStyle: Theme.of(context).textTheme.labelLarge?.copyWith(fontSize: 16),
counterText: '',
filled: true,
fillColor: Theme.of(context).colorScheme.surfaceContainer,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(60),
borderSide: BorderSide.none, // 去掉边框
),
isCollapsed: true,
contentPadding: EdgeInsets.symmetric(vertical: 14, horizontal: 20),
suffixIcon: Container(
padding: EdgeInsets.only(right: 20),
child: suffix,
),
suffixIconConstraints: BoxConstraints(
minWidth: 0,
minHeight: 0,
),
),
);
}
}

View File

@@ -0,0 +1,67 @@
import 'package:flutter/material.dart';
import 'package:food_health/l10n/l10n.dart';
///分割线
class LoginDivider extends StatelessWidget {
const LoginDivider({super.key});
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 20, bottom: 20),
child: Row(
spacing: 8,
children: [
Expanded(
child: Container(
height: 1,
color: Theme.of(context).colorScheme.surfaceContainer,
),
),
Text(
L10n.of.login_other_login,
style: Theme.of(context).textTheme.labelMedium,
),
Expanded(
child: Container(
height: 1,
color: Theme.of(context).colorScheme.surfaceContainer,
),
),
],
),
);
}
}
class OtherButton extends StatelessWidget {
final Function() onTap;
final String icon;
const OtherButton({
super.key,
required this.onTap,
required this.icon,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Container(
width: 45,
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Theme.of(context).colorScheme.surfaceContainer,
),
),
child: AspectRatio(
aspectRatio: 1,
child: Image.asset(icon),
),
),
);
}
}

View File

@@ -0,0 +1,58 @@
import 'package:food_health/stores/app_store.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../../../config/app_context.dart';
import '../../../router/config/route_paths.dart';
import '../../../router/routes.dart';
class SplashPage extends StatefulWidget {
const SplashPage({super.key});
@override
State<SplashPage> createState() => _SplashPageState();
}
class _SplashPageState extends State<SplashPage> {
@override
void initState() {
super.initState();
init();
}
void init() {
WidgetsBinding.instance.addPostFrameCallback((_) async {
AppContext.setContent(navigatorKey.currentState!.context);
//效验
AppStore appStore = context.read<AppStore>();
await appStore.init();
if (!mounted) return;
if (appStore.token.isEmpty) {
context.go(RoutePaths.login);
} else {
context.go(RoutePaths.layout);
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox(
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset(
"assets/image/logo.png",
width: 68.w,
),
],
),
),
);
}
}

View File

@@ -0,0 +1,26 @@
import 'package:flutter/material.dart';
import 'package:food_health/l10n/app_localizations.dart';
class TestPage extends StatefulWidget {
const TestPage({super.key});
@override
State<TestPage> createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(
AppLocalizations.of(context)?.login_title ?? "",
style: TextStyle(
fontSize: 50,
color: Theme.of(context).colorScheme.primary,
),
),
),
);
}
}