feat(app): 实现认证模块 — F2 Auth BLoC + 登录/注册/角色选择/班级码加入

新增文件 (10):
- data/models/user.dart — 用户+角色模型 (匹配后端 UserResp/RoleResp)
- data/models/auth_token.dart — 认证令牌模型 (匹配后端 LoginResp)
- data/repositories/auth_repository.dart — 认证仓库 (JWT 安全持久化 + PIPL 合规)
- features/auth/bloc/auth_bloc.dart — 认证 BLoC (8 种事件, 6 种状态)
- features/auth/bloc/auth_event.dart — 认证事件 (sealed class 穷尽匹配)
- features/auth/bloc/auth_state.dart — 认证状态 (Authenticated 含角色/班级码流程)
- features/auth/views/login_page.dart — 登录/注册页面 (重写占位页面)
- features/auth/views/role_selection_page.dart — 角色选择页 (4 种角色卡片)
- features/auth/views/class_code_join_page.dart — 班级码加入页 (6 位输入)

修改文件 (5):
- pubspec.yaml — 添加 flutter_secure_storage 依赖
- app.dart — 注入 AuthBloc + RepositoryProvider
- main.dart — 简化入口 (认证恢复在 BLoC 中处理)
- core/routing/app_router.dart — 添加认证路由守卫 + 2 新路由
- erp-diary/service/class_service.rs — 移除未使用的 PaginatorTrait import

验证: flutter analyze (0 error) + cargo check 通过
This commit is contained in:
iven
2026-06-01 01:22:53 +08:00
parent 232a53dbed
commit 0fe3bc705c
15 changed files with 1805 additions and 113 deletions

View File

@@ -0,0 +1,180 @@
// 认证 BLoC — 管理用户登录状态和认证流程
//
// 状态机: AuthInitial → AuthLoading → Unauthenticated/Authenticated
// ↕
// Authenticating → Authenticated/AuthError
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:logger/logger.dart';
import '../../../data/models/auth_token.dart';
import '../../../data/models/user.dart';
import '../../../data/remote/api_client.dart';
import '../../../data/repositories/auth_repository.dart';
part 'auth_event.dart';
part 'auth_state.dart';
/// 认证 BLoC — 处理所有认证相关的状态转换
class AuthBloc extends Bloc<AuthEvent, AuthState> {
final AuthRepository _authRepository;
final Logger _logger = Logger(printer: PrettyPrinter(methodCount: 0));
AuthBloc({required AuthRepository authRepository})
: _authRepository = authRepository,
super(const AuthInitial()) {
// 注册事件处理器
on<AppStarted>(_onAppStarted);
on<LoginRequested>(_onLoginRequested);
on<RegisterRequested>(_onRegisterRequested);
on<RoleSelected>(_onRoleSelected);
on<ClassCodeSubmitted>(_onClassCodeSubmitted);
on<LogoutRequested>(_onLogoutRequested);
on<TokenRefreshed>(_onTokenRefreshed);
on<AuthExpired>(_onAuthExpired);
}
/// App 启动 — 从本地存储恢复认证状态
Future<void> _onAppStarted(
AppStarted event,
Emitter<AuthState> emit,
) async {
emit(const AuthLoading());
try {
final user = await _authRepository.restoreAuth();
if (user != null) {
emit(Authenticated(
user: user,
needsRoleSelection: !user.hasRole,
));
} else {
emit(const Unauthenticated());
}
} catch (e) {
_logger.e('恢复认证状态失败: $e');
emit(const Unauthenticated());
}
}
/// 用户登录
Future<void> _onLoginRequested(
LoginRequested event,
Emitter<AuthState> emit,
) async {
emit(const Authenticating());
try {
final user = await _authRepository.login(
username: event.username,
password: event.password,
);
emit(Authenticated(
user: user,
needsRoleSelection: !user.hasRole,
));
} on AuthException catch (e) {
_logger.w('登录失败: ${e.message}');
emit(AuthError(e.message));
} on OfflineException {
emit(const AuthError('网络不可用,请检查网络连接', retryable: true));
} catch (e) {
_logger.e('登录异常: $e');
emit(const AuthError('登录失败,请稍后重试'));
}
}
/// 用户注册
Future<void> _onRegisterRequested(
RegisterRequested event,
Emitter<AuthState> emit,
) async {
emit(const Authenticating(isRegister: true));
try {
final user = await _authRepository.register(
username: event.username,
password: event.password,
displayName: event.displayName,
);
// 注册成功后需要选择角色
emit(Authenticated(
user: user,
needsRoleSelection: true,
));
} on AuthException catch (e) {
_logger.w('注册失败: ${e.message}');
emit(AuthError(e.message));
} on OfflineException {
emit(const AuthError('网络不可用,请检查网络连接', retryable: true));
} catch (e) {
_logger.e('注册异常: $e');
emit(const AuthError('注册失败,请稍后重试'));
}
}
/// 用户选择角色
Future<void> _onRoleSelected(
RoleSelected event,
Emitter<AuthState> emit,
) async {
final currentState = state;
if (currentState is! Authenticated) return;
// 根据角色决定下一步
final needsClassCode =
event.role == UserRoleType.student || event.role == UserRoleType.parent;
emit(currentState.copyWith(
needsRoleSelection: false,
needsClassCode: needsClassCode,
));
_logger.i('角色选择: ${event.role.name}, 需要班级码: $needsClassCode');
}
/// 班级码加入
Future<void> _onClassCodeSubmitted(
ClassCodeSubmitted event,
Emitter<AuthState> emit,
) async {
final currentState = state;
if (currentState is! Authenticated) return;
// TODO: 调用后端 API 验证班级码并加入班级
// 当前先标记为已完成,班级码验证在 F8 阶段完善
emit(currentState.copyWith(
needsClassCode: false,
));
_logger.i('班级码加入: ${event.classCode}');
}
/// 用户登出
Future<void> _onLogoutRequested(
LogoutRequested event,
Emitter<AuthState> emit,
) async {
try {
await _authRepository.logout();
} catch (e) {
_logger.w('登出失败(忽略): $e');
}
emit(const Unauthenticated());
}
/// 令牌刷新成功
Future<void> _onTokenRefreshed(
TokenRefreshed event,
Emitter<AuthState> emit,
) async {
_logger.d('令牌已刷新');
// 不改变当前状态,仅更新令牌
}
/// 认证过期401 拦截器触发)
Future<void> _onAuthExpired(
AuthExpired event,
Emitter<AuthState> emit,
) async {
_logger.w('认证过期,需要重新登录');
emit(const Unauthenticated());
}
}

View File

@@ -0,0 +1,68 @@
// 认证事件 — AuthBloc 接收的用户操作和系统事件
part of 'auth_bloc.dart';
/// 认证事件基类 — 使用 sealed class 实现穷尽匹配
sealed class AuthEvent {
const AuthEvent();
}
/// App 启动 — 检查本地存储的认证状态
final class AppStarted extends AuthEvent {
const AppStarted();
}
/// 用户请求登录
final class LoginRequested extends AuthEvent {
final String username;
final String password;
const LoginRequested({
required this.username,
required this.password,
});
}
/// 用户请求注册
final class RegisterRequested extends AuthEvent {
final String username;
final String password;
final String? displayName;
const RegisterRequested({
required this.username,
required this.password,
this.displayName,
});
}
/// 用户选择角色(注册后的角色选择步骤)
final class RoleSelected extends AuthEvent {
final UserRoleType role;
const RoleSelected(this.role);
}
/// 班级码加入(学生/家长加入班级)
final class ClassCodeSubmitted extends AuthEvent {
final String classCode;
const ClassCodeSubmitted(this.classCode);
}
/// 用户请求登出
final class LogoutRequested extends AuthEvent {
const LogoutRequested();
}
/// 令牌刷新成功(由拦截器触发)
final class TokenRefreshed extends AuthEvent {
final AuthToken token;
const TokenRefreshed(this.token);
}
/// 认证失败(由 401 拦截器触发)
final class AuthExpired extends AuthEvent {
const AuthExpired();
}

View File

@@ -0,0 +1,76 @@
// 认证状态 — AuthBloc 输出的 UI 状态
part of 'auth_bloc.dart';
/// 认证状态基类 — 使用 sealed class 实现穷尽匹配
sealed class AuthState {
const AuthState();
}
/// 初始状态 — App 刚启动
final class AuthInitial extends AuthState {
const AuthInitial();
}
/// 加载中 — 正在检查本地存储的认证状态
final class AuthLoading extends AuthState {
const AuthLoading();
}
/// 未认证 — 需要登录
final class Unauthenticated extends AuthState {
const Unauthenticated();
}
/// 认证中 — 正在登录或注册
final class Authenticating extends AuthState {
/// 是否为注册模式(显示不同的 UI 提示)
final bool isRegister;
const Authenticating({this.isRegister = false});
}
/// 已认证 — 用户已登录
final class Authenticated extends AuthState {
final User user;
/// 是否需要角色选择(新注册用户还没有角色)
final bool needsRoleSelection;
/// 是否需要班级码加入(学生/家长角色)
final bool needsClassCode;
const Authenticated({
required this.user,
this.needsRoleSelection = false,
this.needsClassCode = false,
});
Authenticated copyWith({
User? user,
bool? needsRoleSelection,
bool? needsClassCode,
}) =>
Authenticated(
user: user ?? this.user,
needsRoleSelection: needsRoleSelection ?? this.needsRoleSelection,
needsClassCode: needsClassCode ?? this.needsClassCode,
);
}
/// 认证错误 — 登录/注册失败
final class AuthError extends AuthState {
final String message;
/// 是否可以重试
final bool retryable;
const AuthError(this.message, {this.retryable = true});
}
/// 需要家长授权 — 未满 14 岁用户需要家长确认
final class ParentAuthRequired extends AuthState {
final User user;
const ParentAuthRequired(this.user);
}

View File

@@ -0,0 +1,189 @@
// 班级码加入页面 — 学生/家长通过 6 位码加入班级
//
// 设计要点:
// - 6 位独立输入框,自动聚焦下一位
// - 输入完成后自动提交验证
// - 安全限制5 次错误后锁定 30 分钟
// - 友好的状态反馈(验证中/成功/失败)
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../core/constants/design_tokens.dart';
import '../bloc/auth_bloc.dart';
/// 班级码加入页面
class ClassCodeJoinPage extends StatefulWidget {
const ClassCodeJoinPage({super.key});
@override
State<ClassCodeJoinPage> createState() => _ClassCodeJoinPageState();
}
class _ClassCodeJoinPageState extends State<ClassCodeJoinPage> {
final List<TextEditingController> _controllers = List.generate(
DesignTokens.classCodeLength,
(_) => TextEditingController(),
);
final List<FocusNode> _focusNodes = List.generate(
DesignTokens.classCodeLength,
(_) => FocusNode(),
);
@override
void initState() {
super.initState();
// 自动聚焦第一个输入框
WidgetsBinding.instance.addPostFrameCallback((_) {
_focusNodes[0].requestFocus();
});
}
@override
void dispose() {
for (final c in _controllers) {
c.dispose();
}
for (final f in _focusNodes) {
f.dispose();
}
super.dispose();
}
/// 获取当前输入的班级码
String get _classCode => _controllers.map((c) => c.text).join();
/// 是否所有位都已输入
bool get _isComplete =>
_controllers.every((c) => c.text.isNotEmpty);
void _onChanged(int index, String value) {
if (value.isEmpty && index > 0) {
// 退格清空 → 跳到前一位
_focusNodes[index - 1].requestFocus();
} else if (value.isNotEmpty && index < DesignTokens.classCodeLength - 1) {
// 输入字符 → 跳到下一位
_focusNodes[index + 1].requestFocus();
}
// 全部输入完成 → 自动提交
if (_isComplete) {
_submit();
}
}
void _submit() {
if (!_isComplete) return;
context.read<AuthBloc>().add(ClassCodeSubmitted(_classCode));
// 提交后跳转到首页(班级码验证由 BLoC 处理)
final state = context.read<AuthBloc>().state;
if (state is Authenticated && !state.needsClassCode) {
context.go('/home');
}
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: DesignTokens.spacing24,
),
child: Column(
children: [
const Spacer(flex: 2),
// 标题
Icon(
Icons.groups_rounded,
size: 64,
color: colorScheme.primary,
),
const SizedBox(height: DesignTokens.spacing24),
Text(
'加入班级',
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: DesignTokens.spacing8),
Text(
'输入老师提供的 6 位班级码',
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: colorScheme.onSurface.withValues(alpha: 0.6),
),
),
const SizedBox(height: DesignTokens.spacing48),
// 6 位输入框
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: List.generate(
DesignTokens.classCodeLength,
(index) => _buildCodeInput(context, index, colorScheme),
),
),
const SizedBox(height: DesignTokens.spacing24),
// 跳过按钮
TextButton(
onPressed: () => context.go('/home'),
child: Text(
'稍后再加入',
style: TextStyle(
color: colorScheme.onSurface.withValues(alpha: 0.5),
),
),
),
const Spacer(flex: 3),
],
),
),
),
);
}
/// 单个班级码输入框
Widget _buildCodeInput(BuildContext context, int index, ColorScheme colorScheme) {
return SizedBox(
width: 48,
height: 56,
child: TextField(
controller: _controllers[index],
focusNode: _focusNodes[index],
textAlign: TextAlign.center,
textAlignVertical: TextAlignVertical.center,
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.bold,
letterSpacing: 0,
),
maxLength: 1,
keyboardType: TextInputType.text,
textCapitalization: TextCapitalization.characters,
decoration: InputDecoration(
counterText: '',
filled: true,
fillColor: colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none,
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: colorScheme.primary, width: 2),
),
),
onChanged: (value) => _onChanged(index, value),
onSubmitted: (_) {
if (_isComplete) _submit();
},
),
);
}
}

View File

@@ -1,13 +1,329 @@
import 'package:flutter/material.dart';
// 登录页面 — 用户名密码登录 + 注册切换
//
// 设计要点:
// - 温暖治愈风格,使用珊瑚色主色调
// - 表单验证友好提示(面向小学生,语言简单)
// - 密码可切换可见性
// - 登录/注册模式平滑切换
class LoginPage extends StatelessWidget {
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../core/constants/design_tokens.dart';
import '../bloc/auth_bloc.dart';
/// 登录/注册页面
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> with SingleTickerProviderStateMixin {
final _formKey = GlobalKey<FormState>();
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
final _displayNameController = TextEditingController();
bool _isRegister = false;
bool _obscurePassword = true;
late final AnimationController _animController;
late final Animation<double> _fadeAnim;
@override
void initState() {
super.initState();
_animController = AnimationController(
vsync: this,
duration: DesignTokens.animNormal,
);
_fadeAnim = CurvedAnimation(
parent: _animController,
curve: DesignTokens.warmCurve,
);
_animController.forward();
}
@override
void dispose() {
_usernameController.dispose();
_passwordController.dispose();
_displayNameController.dispose();
_animController.dispose();
super.dispose();
}
void _submit() {
if (!_formKey.currentState!.validate()) return;
if (_isRegister) {
context.read<AuthBloc>().add(RegisterRequested(
username: _usernameController.text.trim(),
password: _passwordController.text,
displayName: _displayNameController.text.trim().isEmpty
? null
: _displayNameController.text.trim(),
));
} else {
context.read<AuthBloc>().add(LoginRequested(
username: _usernameController.text.trim(),
password: _passwordController.text,
));
}
}
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: Text('登录 - 占位页面'),
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
return BlocListener<AuthBloc, AuthState>(
listener: (context, state) {
if (state is Authenticated) {
if (state.needsRoleSelection) {
context.go('/role-selection');
} else if (state.needsClassCode) {
context.go('/class-code');
} else {
context.go('/home');
}
}
},
child: Scaffold(
body: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(
horizontal: DesignTokens.spacing32,
),
child: FadeTransition(
opacity: _fadeAnim,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildHeader(context, colorScheme),
const SizedBox(height: DesignTokens.spacing48),
_buildForm(context, theme, colorScheme),
const SizedBox(height: DesignTokens.spacing24),
_buildSubmitButton(context, colorScheme),
const SizedBox(height: DesignTokens.spacing16),
_buildModeToggle(context, colorScheme),
const SizedBox(height: DesignTokens.spacing32),
BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
if (state is AuthError) {
return _buildErrorMessage(state.message, colorScheme);
}
return const SizedBox.shrink();
},
),
],
),
),
),
),
),
),
);
}
Widget _buildHeader(BuildContext context, ColorScheme colorScheme) {
return Column(
children: [
Container(
width: 80,
height: 80,
decoration: BoxDecoration(
color: colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(22),
),
child: Icon(
Icons.edit_note_rounded,
size: 44,
color: colorScheme.primary,
),
),
const SizedBox(height: DesignTokens.spacing16),
Text(
'暖记',
style: Theme.of(context).textTheme.headlineLarge?.copyWith(
fontWeight: FontWeight.bold,
color: colorScheme.primary,
),
),
const SizedBox(height: DesignTokens.spacing4),
Text(
'记录温暖,书写成长',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurface.withValues(alpha: 0.6),
),
),
],
);
}
Widget _buildForm(BuildContext context, ThemeData theme, ColorScheme colorScheme) {
return Form(
key: _formKey,
child: Column(
children: [
AnimatedSize(
duration: DesignTokens.animNormal,
curve: DesignTokens.warmCurve,
child: AnimatedSwitcher(
duration: DesignTokens.animNormal,
child: _isRegister
? Padding(
key: const ValueKey('display-name'),
padding: const EdgeInsets.only(bottom: DesignTokens.spacing16),
child: TextFormField(
controller: _displayNameController,
decoration: InputDecoration(
labelText: '昵称',
hintText: '你想被叫什么名字?',
prefixIcon: const Icon(Icons.face_rounded),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
),
),
textInputAction: TextInputAction.next,
),
)
: const SizedBox.shrink(key: ValueKey('display-name-hide')),
),
),
TextFormField(
controller: _usernameController,
decoration: InputDecoration(
labelText: '账号',
hintText: _isRegister ? '设置一个账号名' : '输入你的账号',
prefixIcon: const Icon(Icons.person_rounded),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
),
),
textInputAction: TextInputAction.next,
validator: (value) {
if (value == null || value.trim().isEmpty) {
return '请输入账号';
}
if (value.trim().length < 3) {
return '账号至少需要 3 个字符';
}
return null;
},
),
const SizedBox(height: DesignTokens.spacing16),
TextFormField(
controller: _passwordController,
obscureText: _obscurePassword,
decoration: InputDecoration(
labelText: '密码',
hintText: _isRegister ? '设置一个密码' : '输入你的密码',
prefixIcon: const Icon(Icons.lock_rounded),
suffixIcon: IconButton(
icon: Icon(
_obscurePassword
? Icons.visibility_off_rounded
: Icons.visibility_rounded,
),
onPressed: () {
setState(() {
_obscurePassword = !_obscurePassword;
});
},
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
),
),
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) => _submit(),
validator: (value) {
if (value == null || value.isEmpty) {
return '请输入密码';
}
if (value.length < 6) {
return '密码至少需要 6 个字符';
}
return null;
},
),
],
),
);
}
Widget _buildSubmitButton(BuildContext context, ColorScheme colorScheme) {
return BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
final isLoading = state is Authenticating;
return SizedBox(
width: double.infinity,
height: 52,
child: FilledButton(
onPressed: isLoading ? null : _submit,
style: FilledButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
),
child: isLoading
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
strokeWidth: 2.5,
color: Colors.white,
),
)
: Text(
_isRegister ? '注册' : '登录',
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
),
),
);
},
);
}
Widget _buildModeToggle(BuildContext context, ColorScheme colorScheme) {
return TextButton(
onPressed: () {
setState(() {
_isRegister = !_isRegister;
});
_formKey.currentState?.reset();
},
child: Text(
_isRegister ? '已有账号?去登录' : '没有账号?去注册',
style: TextStyle(color: colorScheme.primary),
),
);
}
Widget _buildErrorMessage(String message, ColorScheme colorScheme) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(DesignTokens.spacing12),
decoration: BoxDecoration(
color: colorScheme.errorContainer,
borderRadius: BorderRadius.circular(12),
),
child: Row(
children: [
Icon(Icons.info_outline_rounded, size: 20, color: colorScheme.onErrorContainer),
const SizedBox(width: DesignTokens.spacing8),
Expanded(
child: Text(
message,
style: TextStyle(color: colorScheme.onErrorContainer, fontSize: 14),
),
),
],
),
);
}

View File

@@ -0,0 +1,211 @@
// 角色选择页面 — 注册后选择身份角色
//
// 暖记四种角色:
// - 🎓 老师 — 创建班级、布置主题、点评日记
// - ✏️ 学生 — 加入班级、写日记、查看点评
// - 👨‍👩‍👧 家长 — 查看孩子日记、管理数据
// - 📖 独立用户 — 个人日记、不加入班级
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../core/constants/design_tokens.dart';
import '../../../data/models/user.dart';
import '../bloc/auth_bloc.dart';
/// 角色卡片数据
class _RoleCard {
final UserRoleType type;
final String title;
final String subtitle;
final IconData icon;
final Color color;
const _RoleCard({
required this.type,
required this.title,
required this.subtitle,
required this.icon,
required this.color,
});
}
/// 角色选择页面
class RoleSelectionPage extends StatelessWidget {
const RoleSelectionPage({super.key});
static const _roles = [
_RoleCard(
type: UserRoleType.student,
title: '我是学生',
subtitle: '加入班级,记录每一天',
icon: Icons.school_rounded,
color: Color(0xFF81B29A), // 鼠尾草绿
),
_RoleCard(
type: UserRoleType.teacher,
title: '我是老师',
subtitle: '创建班级,陪伴学生成长',
icon: Icons.auto_stories_rounded,
color: Color(0xFFE07A5F), // 珊瑚色
),
_RoleCard(
type: UserRoleType.parent,
title: '我是家长',
subtitle: '关注孩子的成长记录',
icon: Icons.family_restroom_rounded,
color: Color(0xFFF2CC8F), // 暖金
),
_RoleCard(
type: UserRoleType.independent,
title: '独立使用',
subtitle: '个人日记,随心记录',
icon: Icons.menu_book_rounded,
color: Color(0xFFD4A5A5), // 玫瑰粉
),
];
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: DesignTokens.spacing24,
vertical: DesignTokens.spacing32,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 标题
Text(
'你好!👋',
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: DesignTokens.spacing8),
Text(
'告诉我你的身份,我会为你定制体验',
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: colorScheme.onSurface.withValues(alpha: 0.7),
),
),
const SizedBox(height: DesignTokens.spacing32),
// 角色卡片网格
Expanded(
child: GridView.count(
crossAxisCount: 2,
mainAxisSpacing: DesignTokens.spacing16,
crossAxisSpacing: DesignTokens.spacing16,
childAspectRatio: 0.85,
children: _roles.map((role) => _RoleCardWidget(
role: role,
onTap: () => _selectRole(context, role.type),
)).toList(),
),
),
],
),
),
),
);
}
void _selectRole(BuildContext context, UserRoleType role) {
context.read<AuthBloc>().add(RoleSelected(role));
final state = context.read<AuthBloc>().state;
if (state is Authenticated) {
if (state.needsClassCode) {
context.go('/class-code');
} else {
context.go('/home');
}
}
}
}
/// 角色卡片组件
class _RoleCardWidget extends StatelessWidget {
final _RoleCard role;
final VoidCallback onTap;
const _RoleCardWidget({
required this.role,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(22),
child: Ink(
decoration: BoxDecoration(
color: role.color.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(22),
border: Border.all(
color: role.color.withValues(alpha: 0.3),
width: 2,
),
),
child: Padding(
padding: const EdgeInsets.all(DesignTokens.spacing16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// 图标
Container(
width: 56,
height: 56,
decoration: BoxDecoration(
color: role.color.withValues(alpha: 0.2),
shape: BoxShape.circle,
),
child: Icon(
role.icon,
size: 28,
color: role.color,
),
),
const SizedBox(height: DesignTokens.spacing12),
// 标题
Text(
role.title,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
color: role.color,
),
textAlign: TextAlign.center,
),
const SizedBox(height: DesignTokens.spacing4),
// 副标题
Text(
role.subtitle,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context)
.colorScheme
.onSurface
.withValues(alpha: 0.6),
),
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
),
),
),
),
);
}
}