fix:登录和toast

This commit is contained in:
jingyun
2026-06-07 12:03:23 +08:00
parent 6c943f8394
commit 1f28a64e4f
6 changed files with 374 additions and 106 deletions
+342 -101
View File
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_hooks/flutter_hooks.dart';
@@ -17,34 +19,85 @@ import '../../widgets/page_header.dart';
import '../../widgets/states.dart'; import '../../widgets/states.dart';
class LoginPage extends HookConsumerWidget { class LoginPage extends HookConsumerWidget {
const LoginPage({super.key}); const LoginPage({super.key, this.next});
final String? next;
String _backTargetFromNext() {
final rawNext = next;
if (rawNext == null || rawNext.isEmpty) return AppRoutes.profile;
final decoded = Uri.decodeComponent(rawNext);
final uri = Uri.tryParse(decoded);
if (uri == null) return AppRoutes.profile;
if (!uri.path.startsWith('/')) return AppRoutes.profile;
return decoded;
}
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final phoneController = useTextEditingController(); final phoneController = useTextEditingController();
final codeController = useTextEditingController(); final codeController = useTextEditingController();
final codeFocusNode = useFocusNode();
final codeSent = useState(false);
final sendingCode = useState(false);
final verifying = useState(false);
final countdown = useState(0);
final error = useState<String?>(null);
final agreed = useState(false); final agreed = useState(false);
final loading = useState(false); final timerRef = useRef<Timer?>(null);
final theme = ShadTheme.of(context);
final auth = ref.watch(authControllerProvider); final auth = ref.watch(authControllerProvider);
final theme = ShadTheme.of(context);
Future<void> submit() async { useEffect(() {
return () {
timerRef.value?.cancel();
};
}, const []);
Future<void> sendCode() async {
final phone = phoneController.text.trim(); final phone = phoneController.text.trim();
final code = codeController.text.trim(); if (phone.length != 11) {
if (phone.length < 8) { error.value = '请输入正确的手机号';
showAppToast(context, '请输入手机号');
return; return;
} }
if (code.length < 4) { sendingCode.value = true;
showAppToast(context, '请输入验证码'); error.value = null;
try {
codeSent.value = true;
countdown.value = 60;
timerRef.value?.cancel();
timerRef.value = Timer.periodic(const Duration(seconds: 1), (timer) {
if (countdown.value <= 1) {
timer.cancel();
countdown.value = 0;
} else {
countdown.value = countdown.value - 1;
}
});
codeFocusNode.requestFocus();
} finally {
sendingCode.value = false;
}
}
Future<void> verify() async {
final phone = phoneController.text.trim();
final code = codeController.text.trim();
if (phone.length != 11) {
error.value = '请输入正确的手机号';
return;
}
if (code.length != 6) {
error.value = '请输入 6 位验证码';
return; return;
} }
if (!agreed.value) { if (!agreed.value) {
showAppToast(context, '请先同意用户协议和隐私政策'); error.value = '请先同意用户协议和隐私政策';
return; return;
} }
loading.value = true; verifying.value = true;
error.value = null;
try { try {
await ref await ref
.read(authControllerProvider.notifier) .read(authControllerProvider.notifier)
@@ -52,117 +105,305 @@ class LoginPage extends HookConsumerWidget {
await ref.read(profileControllerProvider.notifier).refresh(); await ref.read(profileControllerProvider.notifier).refresh();
if (!context.mounted) return; if (!context.mounted) return;
showAppToast(context, '已登录 ${maskPhone(phone)}'); showAppToast(context, '已登录 ${maskPhone(phone)}');
if (context.canPop()) { final nextPath = next?.trim();
if (nextPath != null && nextPath.isNotEmpty) {
context.go(Uri.decodeComponent(nextPath));
} else if (context.canPop()) {
context.pop(); context.pop();
} else { } else {
context.go(AppRoutes.profile); context.go(AppRoutes.profile);
} }
} finally { } finally {
loading.value = false; verifying.value = false;
} }
} }
return Scaffold( Future<void> submitLogin() async {
backgroundColor: theme.colorScheme.background, final phone = phoneController.text.trim();
appBar: AppBar( final code = codeController.text.trim();
leading: IconButton( if (phone.length != 11) {
icon: const Icon(AppIcons.arrowLeft), error.value = '请输入正确的手机号';
onPressed: () { return;
if (context.canPop()) { }
context.pop(); if (code.length != 6) {
} else { error.value = '请输入 6 位验证码';
context.go(AppRoutes.profile); return;
} }
}, await verify();
), }
title: const Text('登录 · Login'),
), void showPrivacyCheckDialog(VoidCallback onAgreed) {
body: ListView( showModalBottomSheet<void>(
padding: const EdgeInsets.fromLTRB( context: context,
YantingSpacing.screenX, enableDrag: false,
4, barrierColor: Colors.black.withValues(alpha: 0.75),
YantingSpacing.screenX, builder: (innerContext) => SafeArea(
20, child: SingleChildScrollView(
), child: Padding(
children: [ padding: const EdgeInsets.fromLTRB(22, 28, 22, 24),
const PageHeader(title: '登录研听', subtitle: '先把登录逻辑接通,弹窗入口保持不变'),
if (auth.loggedIn) ...[
AppCard(
color: theme.colorScheme.secondary,
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text('当前已登录', style: YantingText.cardTitle), Center(
const SizedBox(height: 6), child: Text(
Text( '请阅读并同意以下条款',
auth.phone == null style: Theme.of(context).textTheme.titleMedium?.copyWith(
? '本地登录态已生效' fontWeight: FontWeight.w500,
: '手机号 ${maskPhone(auth.phone!)}', ),
style: YantingText.body.copyWith( ),
color: theme.colorScheme.mutedForeground, ),
const SizedBox(height: 14),
Center(
child: Text.rich(
textAlign: TextAlign.center,
TextSpan(
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: theme.colorScheme.mutedForeground,
height: 1.7,
fontSize: 12,
),
children: [
const TextSpan(text: '登录前需要先阅读并同意 '),
TextSpan(
text: '《用户协议》',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: theme.colorScheme.primary,
fontSize: 12,
decoration: TextDecoration.underline,
decorationColor: theme.colorScheme.primary,
),
),
const TextSpan(text: ''),
TextSpan(
text: '《隐私政策》',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: theme.colorScheme.primary,
fontSize: 12,
decoration: TextDecoration.underline,
decorationColor: theme.colorScheme.primary,
),
),
],
),
),
),
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
child: AppButton(
label: '同意并发送验证码',
expand: true,
onPressed: () {
Navigator.of(innerContext).pop();
agreed.value = true;
onAgreed();
},
), ),
), ),
], ],
), ),
), ),
const SizedBox(height: YantingSpacing.x3), ),
], ),
AppCard( );
padding: const EdgeInsets.all(18), }
child: Column(
crossAxisAlignment: CrossAxisAlignment.start, Future<void> onSendCodeTap() async {
children: [ if (sendingCode.value || countdown.value > 0) return;
Text('手机号登录', style: YantingText.sectionTitle), if (!agreed.value) {
const SizedBox(height: 12), showPrivacyCheckDialog(() {
ShadInput( unawaited(sendCode());
controller: phoneController, });
placeholder: const Text('请输入手机号'), return;
keyboardType: TextInputType.phone, }
inputFormatters: [FilteringTextInputFormatter.digitsOnly], unawaited(sendCode());
}
final clickable = !sendingCode.value && !verifying.value;
return PopScope(
canPop: (next ?? '').isEmpty,
onPopInvokedWithResult: (didPop, _) {
if (didPop) return;
if (!context.mounted) return;
final nextPath = next;
if (nextPath != null && nextPath.isNotEmpty) {
context.go(_backTargetFromNext());
return;
}
if (context.canPop()) {
context.pop();
return;
}
context.go(AppRoutes.profile);
},
child: Scaffold(
backgroundColor: theme.colorScheme.background,
appBar: AppBar(
leading: IconButton(
icon: const Icon(AppIcons.arrowLeft),
onPressed: () {
final nextPath = next;
if (nextPath != null && nextPath.isNotEmpty) {
context.go(_backTargetFromNext());
return;
}
if (context.canPop()) {
context.pop();
} else {
context.go(AppRoutes.profile);
}
},
),
title: const Text('登录 · Login'),
),
body: ListView(
padding: const EdgeInsets.fromLTRB(
YantingSpacing.screenX,
4,
YantingSpacing.screenX,
20,
),
children: [
const PageHeader(title: '登录研听', subtitle: '先把登录逻辑接通,弹窗入口保持不变'),
if (auth.loggedIn) ...[
AppCard(
color: theme.colorScheme.secondary,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('当前已登录', style: YantingText.cardTitle),
const SizedBox(height: 6),
Text(
auth.phone == null
? '本地登录态已生效'
: '手机号 ${maskPhone(auth.phone!)}',
style: YantingText.body.copyWith(
color: theme.colorScheme.mutedForeground,
),
),
],
), ),
const SizedBox(height: 12), ),
ShadInput( const SizedBox(height: YantingSpacing.x3),
controller: codeController, ],
placeholder: const Text('验证码'), AppCard(
keyboardType: TextInputType.number, padding: const EdgeInsets.all(18),
inputFormatters: [FilteringTextInputFormatter.digitsOnly], child: Column(
trailing: Padding( crossAxisAlignment: CrossAxisAlignment.start,
padding: const EdgeInsets.only(right: 4), children: [
child: AppButton( Text('手机号登录', style: YantingText.sectionTitle),
label: '发送验证码', const SizedBox(height: 12),
kind: AppButtonKind.ghost, ShadInput(
compact: true, controller: phoneController,
onPressed: () => showAppToast(context, '验证码功能待接入'), placeholder: const Text('请输入手机号'),
keyboardType: TextInputType.phone,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
),
const SizedBox(height: 12),
ShadInput(
controller: codeController,
focusNode: codeFocusNode,
placeholder: const Text('验证码'),
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
trailing: Padding(
padding: const EdgeInsets.only(right: 4),
child: AppButton(
label: countdown.value > 0
? '${countdown.value}s'
: '发送验证码',
kind: AppButtonKind.ghost,
compact: true,
onPressed: onSendCodeTap,
),
), ),
), ),
), const SizedBox(height: 14),
const SizedBox(height: 14), Row(
ShadCheckbox( crossAxisAlignment: CrossAxisAlignment.start,
value: agreed.value, children: [
onChanged: (value) => agreed.value = value, Padding(
label: const Text('我已阅读并同意'), padding: const EdgeInsets.only(top: 2),
sublabel: const Text('《用户协议》和《隐私政策》'), child: ShadCheckbox(
), value: agreed.value,
const SizedBox(height: 18), onChanged: (value) => agreed.value = value,
AppButton( ),
label: loading.value ? '登录中...' : '登录', ),
expand: true, const SizedBox(width: 10),
onPressed: loading.value ? null : submit, Expanded(
), child: Text.rich(
], TextSpan(
), style: YantingText.meta.copyWith(
), color: theme.colorScheme.mutedForeground,
const SizedBox(height: YantingSpacing.x3), height: 1.7,
AppCard( ),
color: theme.colorScheme.secondary, children: [
child: Text( const TextSpan(text: '已阅读并同意 '),
'当前版本先做本地登录态和页面流转,后端接口接入后再替换为真实校验。', TextSpan(
style: YantingText.meta.copyWith( text: '《用户协议》',
color: theme.colorScheme.mutedForeground, style: YantingText.meta.copyWith(
color: theme.colorScheme.primary,
),
),
const TextSpan(text: ''),
TextSpan(
text: '《隐私政策》',
style: YantingText.meta.copyWith(
color: theme.colorScheme.primary,
),
),
],
),
),
),
],
),
if (error.value != null) ...[
const SizedBox(height: 10),
Text(
error.value!,
style: YantingText.meta.copyWith(
color: theme.colorScheme.destructive,
),
),
],
const SizedBox(height: 18),
AppButton(
label: verifying.value ? '登录中...' : '登录',
expand: true,
onPressed: clickable
? () {
if (!agreed.value) {
showPrivacyCheckDialog(() {
unawaited(submitLogin());
});
return;
}
unawaited(submitLogin());
}
: null,
kind: AppButtonKind.primary,
),
],
), ),
), ),
), const SizedBox(height: YantingSpacing.x3),
], AppCard(
color: theme.colorScheme.secondary,
child: Text(
codeSent.value
? '验证码逻辑已接通,当前先用本地登录态串起页面流转。'
: '当前版本先做本地登录态和页面流转,后端接口接入后再替换为真实校验。',
style: YantingText.meta.copyWith(
color: theme.colorScheme.mutedForeground,
),
),
),
],
),
), ),
); );
} }
+3 -1
View File
@@ -103,7 +103,9 @@ class ProfilePage extends ConsumerWidget {
AppButton( AppButton(
label: '登录 / 注册', label: '登录 / 注册',
expand: true, expand: true,
onPressed: () => context.push(AppRoutes.login), onPressed: () => context.push(
'${AppRoutes.login}?next=${Uri.encodeComponent(AppRoutes.profile)}',
),
), ),
], ],
const SizedBox(height: 18), const SizedBox(height: 18),
+7 -2
View File
@@ -151,8 +151,13 @@ final routerProvider = Provider<GoRouter>((ref) {
), ),
GoRoute( GoRoute(
path: AppRoutes.login, path: AppRoutes.login,
pageBuilder: (context, state) => pageBuilder: (context, state) {
_slidePage(state: state, child: const LoginPage()), final next = state.uri.queryParameters['next'];
return _slidePage(
state: state,
child: LoginPage(next: next),
);
},
), ),
GoRoute( GoRoute(
path: AppRoutes.institutionDetail, path: AppRoutes.institutionDetail,
+13 -2
View File
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shadcn_ui/shadcn_ui.dart'; import 'package:shadcn_ui/shadcn_ui.dart';
import '../theme/yanting_tokens.dart'; import '../theme/yanting_tokens.dart';
@@ -176,6 +177,16 @@ class ErrorState extends StatelessWidget {
} }
} }
void showAppToast(BuildContext context, String message) { Future<bool?> showAppToast(BuildContext context, String message) {
ShadToaster.of(context).show(ShadToast(title: Text(message))); // ShadToaster.of(context).show(ShadToast(title: Text(message)));
return Fluttertoast.showToast(
msg: message,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: const Color(0xCC111111),
textColor: Colors.white,
fontSize: 16,
);
} }
+8
View File
@@ -181,6 +181,14 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" version: "0.0.0"
fluttertoast:
dependency: "direct main"
description:
name: fluttertoast
sha256: "144ddd74d49c865eba47abe31cbc746c7b311c82d6c32e571fd73c4264b740e2"
url: "https://pub.dev"
source: hosted
version: "9.0.0"
go_router: go_router:
dependency: "direct main" dependency: "direct main"
description: description:
+1
View File
@@ -44,6 +44,7 @@ dependencies:
remixicon: ^4.9.3 remixicon: ^4.9.3
shared_preferences: ^2.3.3 shared_preferences: ^2.3.3
shadcn_ui: ^0.53.6 shadcn_ui: ^0.53.6
fluttertoast: ^9.0.0
dev_dependencies: dev_dependencies:
flutter_test: flutter_test: