#first commit
This commit is contained in:
17
lib/core/app/app_cubit.dart
Normal file
17
lib/core/app/app_cubit.dart
Normal file
@@ -0,0 +1,17 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../domain/entities/user_entity.dart';
|
||||
import 'app_state.dart';
|
||||
|
||||
class AppCubit extends Cubit<AppState> {
|
||||
AppCubit() : super(const AppState());
|
||||
|
||||
// 传入实体对象,而不是零散的 id
|
||||
void setAuth(UserEntity user) {
|
||||
emit(state.copyWith(user));
|
||||
}
|
||||
|
||||
void clearAuth() {
|
||||
emit(const AppState());
|
||||
}
|
||||
}
|
||||
20
lib/core/app/app_state.dart
Normal file
20
lib/core/app/app_state.dart
Normal file
@@ -0,0 +1,20 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
import '../domain/entities/user_entity.dart';
|
||||
|
||||
class AppState extends Equatable {
|
||||
final UserEntity? user; // 直接存实体,包含 userId, username,token 等所有信息
|
||||
|
||||
const AppState({this.user});
|
||||
|
||||
// 辅助属性:判断是否登录
|
||||
bool get isLoggedIn => user != null;
|
||||
|
||||
AppState copyWith(UserEntity? user) {
|
||||
return AppState(user: user ?? this.user);
|
||||
}
|
||||
|
||||
// 必须重写 props,UI 才会只在数据真正变化时刷新
|
||||
@override
|
||||
List<Object?> get props => [user];
|
||||
}
|
||||
4
lib/core/consts/tcp_consts.dart
Normal file
4
lib/core/consts/tcp_consts.dart
Normal file
@@ -0,0 +1,4 @@
|
||||
class TCPConsts {
|
||||
static const String TCP_IP = "1.95.137.212";
|
||||
static const int TCP_PORT = 9001;
|
||||
}
|
||||
83
lib/core/di/injection.dart
Normal file
83
lib/core/di/injection.dart
Normal file
@@ -0,0 +1,83 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../features/auth/data/datasources/auth_http_datasource.dart';
|
||||
import '../../features/auth/data/datasources/impl/auth_http_datasource_impl.dart';
|
||||
import '../../features/auth/data/repositories/auth_repository_impl.dart';
|
||||
import '../../features/auth/domain/repositories/auth_repository.dart';
|
||||
import '../../features/auth/domain/usecases/login_usecase.dart';
|
||||
import '../../features/auth/presentation/bloc/auth_cubit.dart';
|
||||
import '../../features/auth/presentation/bloc/login_bloc.dart';
|
||||
import '../../features/auth/presentation/bloc/login_cubit.dart';
|
||||
import '../app/app_cubit.dart';
|
||||
import '../network/dio_client.dart';
|
||||
import '../network/net_message_dispatcher.dart';
|
||||
import '../network/tcp/tcp_client.dart';
|
||||
import '../router/app_router.dart';
|
||||
import '../storage/impl/user_storage_impl.dart';
|
||||
import '../storage/user_storage.dart';
|
||||
|
||||
final sl = GetIt.instance;
|
||||
|
||||
Future<void> init() async {
|
||||
/// 1. 底层工具与存储 (最底层)
|
||||
/// 1.1 --- Network ---
|
||||
/// 1.1.1 Dio:Http客户端
|
||||
sl.registerLazySingleton<Dio>(() => DioClient.create());
|
||||
|
||||
/// 1.1.2 TcpClient:TCP客户端
|
||||
sl.registerLazySingleton(() => TcpClient());
|
||||
|
||||
/// 1.1.3 NetMessageDispatcher:消息调度器,并将 TcpClient 注入给它
|
||||
sl.registerLazySingleton(() => NetMessageDispatcher(sl()));
|
||||
|
||||
/// 1.2 --- 本地存储 (LocalStorage) ---
|
||||
/// 1.2.1 SharedPreferences:本地存储库
|
||||
final sharedPrefs = await SharedPreferences.getInstance();
|
||||
sl.registerLazySingleton<SharedPreferences>(() => sharedPrefs);
|
||||
|
||||
/// 1.2.2 UserStorage:用户存储库
|
||||
sl.registerLazySingleton<UserStorage>(
|
||||
// 必须先注册上面本地存储库的实例
|
||||
() => UserStorageImpl(sl<SharedPreferences>()),
|
||||
);
|
||||
|
||||
/// 2. 数据源 (DataSource)
|
||||
sl.registerLazySingleton<AuthHttpDataSource>(
|
||||
() => AuthHttpDataSourceImpl(sl()),
|
||||
);
|
||||
|
||||
/// 3. 仓库 (Repository)
|
||||
sl.registerLazySingleton<AuthRepository>(
|
||||
() => AuthRepositoryImpl(
|
||||
remote: sl(), // 自动寻找已注册的 LoginRemoteDataSource
|
||||
localTokenStorage: sl(), // 自动寻找已注册的 TokenStorage
|
||||
),
|
||||
);
|
||||
|
||||
/// 4. 用例 (UseCase)
|
||||
sl.registerLazySingleton(() => LoginUseCase(sl()));
|
||||
|
||||
/// 5. 状态管理 (Cubit/Bloc)
|
||||
sl.registerLazySingleton(() => AppCubit()); // AuthCubit 依赖它,必须先注册
|
||||
|
||||
/// 6. 认证 (Auth)
|
||||
// --- 关键修改点 1: AuthCubit 必须在 GoRouter 之前注册,并传入参数 ---
|
||||
sl.registerLazySingleton(
|
||||
() => AuthCubit(
|
||||
sl<UserStorage>(),
|
||||
sl<TcpClient>(),
|
||||
sl<AppCubit>(),
|
||||
sl<NetMessageDispatcher>(),
|
||||
),
|
||||
);
|
||||
|
||||
/// 7. 路由 (Router)
|
||||
sl.registerSingleton<GoRouter>(createRouter(sl<AuthCubit>()));
|
||||
|
||||
/// 8. 页面级 Bloc/Cubit (Factory)
|
||||
sl.registerFactory(() => LoginBloc(sl()));
|
||||
sl.registerFactory(() => LoginCubit(sl(), sl()));
|
||||
}
|
||||
32
lib/core/domain/entities/user_entity.dart
Normal file
32
lib/core/domain/entities/user_entity.dart
Normal file
@@ -0,0 +1,32 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class UserEntity extends Equatable {
|
||||
final String userId;
|
||||
final String username;
|
||||
final String nickname;
|
||||
final String token;
|
||||
final String? avatar;
|
||||
final String? email;
|
||||
final String? phone;
|
||||
|
||||
UserEntity({
|
||||
required this.userId,
|
||||
required this.username,
|
||||
required this.nickname,
|
||||
required this.token,
|
||||
this.avatar,
|
||||
this.email,
|
||||
this.phone,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
userId,
|
||||
username,
|
||||
nickname,
|
||||
avatar,
|
||||
token,
|
||||
email,
|
||||
phone,
|
||||
];
|
||||
}
|
||||
5
lib/core/domain/usecases/base_usecase.dart
Normal file
5
lib/core/domain/usecases/base_usecase.dart
Normal file
@@ -0,0 +1,5 @@
|
||||
abstract class BaseUseCase<Type, Params> {
|
||||
Future<Type> call(Params params);
|
||||
}
|
||||
|
||||
class NoParams {}
|
||||
4
lib/core/error/failure.dart
Normal file
4
lib/core/error/failure.dart
Normal file
@@ -0,0 +1,4 @@
|
||||
class Failure {
|
||||
final String message;
|
||||
Failure(this.message);
|
||||
}
|
||||
16
lib/core/network/dio_client.dart
Normal file
16
lib/core/network/dio_client.dart
Normal file
@@ -0,0 +1,16 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
class DioClient {
|
||||
static Dio create() {
|
||||
final dio = Dio(
|
||||
BaseOptions(
|
||||
baseUrl: 'http://1.95.137.212:8081',
|
||||
connectTimeout: const Duration(seconds: 5),
|
||||
receiveTimeout: const Duration(seconds: 5),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
),
|
||||
);
|
||||
dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
|
||||
return dio;
|
||||
}
|
||||
}
|
||||
26
lib/core/network/net_message_dispatcher.dart
Normal file
26
lib/core/network/net_message_dispatcher.dart
Normal file
@@ -0,0 +1,26 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'protocol_decoder.dart';
|
||||
import 'tcp/tcp_client.dart';
|
||||
// 注意:这里需要导入你具体的 UserModel
|
||||
// import '../../features/auth/data/models/user_model.dart';
|
||||
|
||||
class NetMessageDispatcher {
|
||||
final TcpClient tcpClient;
|
||||
NetMessageDispatcher(this.tcpClient);
|
||||
|
||||
/// 过滤特定指令的流
|
||||
Stream<RawPacket> onCommand(int commandCode) {
|
||||
return tcpClient.packetStream.where((p) => p.command == commandCode);
|
||||
}
|
||||
|
||||
/// 示例解析方法:将 0x02 指令解析为 String
|
||||
Stream<String> onStringMessage() {
|
||||
return onCommand(0x02).map((p) => utf8.decode(p.payload));
|
||||
}
|
||||
|
||||
/// 示例解析方法:将 0x12 指令解析为 JSON 并转为模型
|
||||
Stream<Map<String, dynamic>> onJsonMessage(int cmd) {
|
||||
return onCommand(cmd).map((p) => jsonDecode(utf8.decode(p.payload)));
|
||||
}
|
||||
}
|
||||
59
lib/core/network/protocol_decoder.dart
Normal file
59
lib/core/network/protocol_decoder.dart
Normal file
@@ -0,0 +1,59 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
class RawPacket {
|
||||
final int command; // 第三位指令位
|
||||
final Uint8List payload; // 数据位
|
||||
RawPacket({required this.command, required this.payload});
|
||||
}
|
||||
|
||||
class ProtocolDecoder {
|
||||
static const head = [0xAB, 0xAA];
|
||||
static const tail = [0xAA, 0xAB];
|
||||
final List<int> _buffer = [];
|
||||
|
||||
List<RawPacket> decode(List<int> newData) {
|
||||
_buffer.addAll(newData);
|
||||
List<RawPacket> packets = [];
|
||||
|
||||
while (_buffer.length >= 5) {
|
||||
// 最小包长度:头2+指令1+尾2 = 5,加1位数据=6,但是心跳包是AB AA FF AA AB
|
||||
// 1. 找头
|
||||
int headIdx = -1;
|
||||
for (int i = 0; i < _buffer.length - 1; i++) {
|
||||
if (_buffer[i] == head[0] && _buffer[i + 1] == head[1]) {
|
||||
headIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (headIdx == -1) {
|
||||
_buffer.clear(); // 没头,全是垃圾数据
|
||||
break;
|
||||
}
|
||||
|
||||
// 2. 找尾
|
||||
int tailIdx = -1;
|
||||
for (int i = headIdx + 2; i < _buffer.length - 1; i++) {
|
||||
if (_buffer[i] == tail[0] && _buffer[i + 1] == tail[1]) {
|
||||
tailIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (tailIdx != -1) {
|
||||
// 3. 提取
|
||||
int cmd = _buffer[headIdx + 2];
|
||||
Uint8List payload = Uint8List.fromList(
|
||||
_buffer.sublist(headIdx + 3, tailIdx),
|
||||
);
|
||||
packets.add(RawPacket(command: cmd, payload: payload));
|
||||
|
||||
// 4. 移除已处理部分
|
||||
_buffer.removeRange(0, tailIdx + 2);
|
||||
} else {
|
||||
break; // 还没传完
|
||||
}
|
||||
}
|
||||
return packets;
|
||||
}
|
||||
}
|
||||
54
lib/core/network/tcp/tcp_client.dart
Normal file
54
lib/core/network/tcp/tcp_client.dart
Normal file
@@ -0,0 +1,54 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:maibu_satabot_v2/core/network/protocol_decoder.dart';
|
||||
|
||||
class TcpClient {
|
||||
Socket? _socket;
|
||||
final _decoder = ProtocolDecoder();
|
||||
// 使用 StreamController 将原始数据流暴露给外部,以便多个 DataSource 监听
|
||||
final _controller = StreamController<RawPacket>.broadcast();
|
||||
Stream<RawPacket> get packetStream => _controller.stream;
|
||||
|
||||
// 通过参数配置,不硬编码
|
||||
Future<void> connect({required String host, required int port}) async {
|
||||
try {
|
||||
_socket = await Socket.connect(
|
||||
host,
|
||||
port,
|
||||
timeout: const Duration(seconds: 5),
|
||||
);
|
||||
|
||||
_socket!.listen(
|
||||
(data) {
|
||||
var packets = _decoder.decode(data);
|
||||
for (var packet in packets) {
|
||||
_controller.add(packet);
|
||||
}
|
||||
},
|
||||
onDone: disconnect,
|
||||
onError: (e) => disconnect(),
|
||||
);
|
||||
} catch (e) {
|
||||
rethrow; // 向上抛出连接异常
|
||||
}
|
||||
}
|
||||
|
||||
void send(Map<String, dynamic> data) {
|
||||
if (_socket == null) throw Exception("Socket not connected");
|
||||
_socket!.write(jsonEncode(data));
|
||||
}
|
||||
|
||||
void sendRaw(int cmd, List<int> payload) {
|
||||
if (_socket == null) return;
|
||||
// 组装:头 AB AA + 指令 + 数据 + 尾 AA AB
|
||||
final data = [0xAB, 0xAA, cmd, ...payload, 0xAA, 0xAB];
|
||||
_socket!.add(data);
|
||||
}
|
||||
|
||||
void disconnect() {
|
||||
_socket?.destroy();
|
||||
_socket = null;
|
||||
}
|
||||
}
|
||||
33
lib/core/router/app_router.dart
Normal file
33
lib/core/router/app_router.dart
Normal file
@@ -0,0 +1,33 @@
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:maibu_satabot_v2/core/router/route_paths.dart';
|
||||
|
||||
import '../../features/auth/presentation/bloc/auth_cubit.dart';
|
||||
import '../../features/auth/presentation/bloc/auth_state.dart';
|
||||
import '../../features/auth/presentation/pages/login_page.dart';
|
||||
import '../../features/home/presentation/pages/home_page.dart';
|
||||
import '../../features/register/presentation/pages/register_page.dart';
|
||||
import 'go_router_refresh_stream.dart';
|
||||
|
||||
GoRouter createRouter(AuthCubit authCubit) {
|
||||
return GoRouter(
|
||||
initialLocation: RoutePaths.login,
|
||||
refreshListenable: GoRouterRefreshStream(authCubit.stream),
|
||||
redirect: (context, state) {
|
||||
final loggedIn = authCubit.state is AuthAuthenticated;
|
||||
final loggingIn = state.matchedLocation == RoutePaths.login;
|
||||
|
||||
if (!loggedIn && !loggingIn) {
|
||||
return RoutePaths.login;
|
||||
}
|
||||
if (loggedIn && loggingIn) {
|
||||
return RoutePaths.home;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
routes: [
|
||||
GoRoute(path: RoutePaths.login, builder: (_, __) => LoginPage()),
|
||||
GoRoute(path: RoutePaths.register, builder: (_, __) => RegisterPage()),
|
||||
GoRoute(path: RoutePaths.home, builder: (context, state) => HomePage()),
|
||||
],
|
||||
);
|
||||
}
|
||||
19
lib/core/router/go_router_refresh_stream.dart
Normal file
19
lib/core/router/go_router_refresh_stream.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class GoRouterRefreshStream extends ChangeNotifier {
|
||||
late final StreamSubscription _subscription;
|
||||
|
||||
GoRouterRefreshStream(Stream<dynamic> stream) {
|
||||
_subscription = stream.listen((_) {
|
||||
notifyListeners();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_subscription.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
5
lib/core/router/route_paths.dart
Normal file
5
lib/core/router/route_paths.dart
Normal file
@@ -0,0 +1,5 @@
|
||||
class RoutePaths {
|
||||
static const login = '/auth';
|
||||
static const register = '/register';
|
||||
static const home = '/home';
|
||||
}
|
||||
41
lib/core/storage/impl/user_storage_impl.dart
Normal file
41
lib/core/storage/impl/user_storage_impl.dart
Normal file
@@ -0,0 +1,41 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../../features/auth/data/models/user_model.dart';
|
||||
import '../user_storage.dart';
|
||||
|
||||
class UserStorageImpl implements UserStorage {
|
||||
final SharedPreferences _prefs;
|
||||
static const _userKey = 'auth_user';
|
||||
|
||||
UserStorageImpl(this._prefs);
|
||||
|
||||
@override
|
||||
Future<void> saveUser(UserEntity user) async {
|
||||
// 1. 将对象转为 Map -> 2. 将 Map 转为 JSON 字符串
|
||||
final model = UserModel.fromEntity(user);
|
||||
await _prefs.setString(_userKey, json.encode(model.toJson()));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<UserEntity?> getUser() async {
|
||||
final jsonString = _prefs.getString(_userKey);
|
||||
if (jsonString == null) return null;
|
||||
|
||||
// 将 JSON 转回 Model,再转成 Entity 返回给业务层
|
||||
final model = UserModel.fromJson(json.decode(jsonString));
|
||||
return model.toEntity();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> deleteUser() async {
|
||||
await _prefs.remove(_userKey);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> hasUser() async {
|
||||
return _prefs.containsKey(_userKey);
|
||||
}
|
||||
}
|
||||
8
lib/core/storage/user_storage.dart
Normal file
8
lib/core/storage/user_storage.dart
Normal file
@@ -0,0 +1,8 @@
|
||||
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
|
||||
|
||||
abstract class UserStorage {
|
||||
Future<void> saveUser(UserEntity user);
|
||||
Future<UserEntity?> getUser();
|
||||
Future<void> deleteUser();
|
||||
Future<bool> hasUser();
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import '../models/user_model.dart';
|
||||
|
||||
abstract class AuthHttpDataSource {
|
||||
Future<UserModel> login(String username, String password, int sourceType);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../models/user_model.dart';
|
||||
import '../auth_http_datasource.dart';
|
||||
|
||||
class AuthHttpDataSourceImpl implements AuthHttpDataSource {
|
||||
final Dio dio;
|
||||
|
||||
AuthHttpDataSourceImpl(this.dio);
|
||||
|
||||
@override
|
||||
Future<UserModel> login(String username, String password, sourceType) async {
|
||||
final response = await dio.post(
|
||||
'/auth',
|
||||
data: {
|
||||
'username': username,
|
||||
'password': password,
|
||||
'sourceType': sourceType,
|
||||
},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
print('runtimeType = ${response.data.runtimeType}');
|
||||
return UserModel.fromJson(response.data);
|
||||
} else {
|
||||
throw Exception(response.data['message'] ?? 'Login failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
62
lib/features/auth/data/models/user_model.dart
Normal file
62
lib/features/auth/data/models/user_model.dart
Normal file
@@ -0,0 +1,62 @@
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
|
||||
class UserModel extends UserEntity {
|
||||
UserModel({
|
||||
required super.userId,
|
||||
required super.username,
|
||||
required super.nickname,
|
||||
required super.token,
|
||||
super.avatar,
|
||||
super.email,
|
||||
super.phone,
|
||||
});
|
||||
|
||||
factory UserModel.fromJson(Map<String, dynamic> json) {
|
||||
print(json);
|
||||
return UserModel(
|
||||
userId: json['userId'],
|
||||
username: json['username'],
|
||||
nickname: json['nickName'],
|
||||
token: json['token'],
|
||||
avatar: json['avatar'],
|
||||
email: json['email'],
|
||||
phone: json['phone'],
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'userId': userId,
|
||||
'username': username,
|
||||
'nickName': nickname,
|
||||
'token': token,
|
||||
'avatar': avatar,
|
||||
'email': email,
|
||||
'phone': phone,
|
||||
};
|
||||
}
|
||||
|
||||
toEntity() {
|
||||
return UserEntity(
|
||||
userId: userId,
|
||||
username: username,
|
||||
nickname: nickname,
|
||||
token: token,
|
||||
avatar: avatar,
|
||||
email: email,
|
||||
phone: phone,
|
||||
);
|
||||
}
|
||||
|
||||
factory UserModel.fromEntity(UserEntity entity) {
|
||||
return UserModel(
|
||||
userId: entity.userId,
|
||||
username: entity.username,
|
||||
nickname: entity.nickname,
|
||||
token: entity.token,
|
||||
avatar: entity.avatar,
|
||||
email: entity.email,
|
||||
phone: entity.phone,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import 'package:maibu_satabot_v2/core/storage/user_storage.dart';
|
||||
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
import '../../domain/repositories/auth_repository.dart';
|
||||
import '../datasources/auth_http_datasource.dart';
|
||||
|
||||
class AuthRepositoryImpl implements AuthRepository {
|
||||
final AuthHttpDataSource remote;
|
||||
final UserStorage localTokenStorage;
|
||||
|
||||
AuthRepositoryImpl({required this.remote, required this.localTokenStorage});
|
||||
|
||||
@override
|
||||
// 注意 1:返回类型应该是 Domain 层的 UserEntity,而不是 UserModel
|
||||
Future<UserEntity> login(
|
||||
String username,
|
||||
String password,
|
||||
int sourceType,
|
||||
) async {
|
||||
try {
|
||||
// 1. 从数据源获取 Data Model
|
||||
final userModel = await remote.login(username, password, sourceType);
|
||||
|
||||
// 2. 职责核心:将 Model 转换为 Entity (解耦业务与 JSON 结构)
|
||||
if (userModel != null) {
|
||||
await localTokenStorage.saveUser(userModel);
|
||||
}
|
||||
|
||||
// 2. 只返回纯粹的用户信息实体
|
||||
return userModel.toEntity();
|
||||
} catch (e) {
|
||||
// 3. 职责核心:异常翻译
|
||||
// 不直接抛出 Dio 异常,而是抛出业务层定义的自定义异常或返回 Failure
|
||||
throw Exception(e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
|
||||
abstract class AuthRepository {
|
||||
Future<UserEntity> login(String username, String password, int sourceType);
|
||||
}
|
||||
26
lib/features/auth/domain/usecases/login_usecase.dart
Normal file
26
lib/features/auth/domain/usecases/login_usecase.dart
Normal file
@@ -0,0 +1,26 @@
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
import '../../../../core/domain/usecases/base_usecase.dart';
|
||||
import '../repositories/auth_repository.dart';
|
||||
|
||||
class LoginUseCase implements BaseUseCase<UserEntity, LoginParams> {
|
||||
final AuthRepository repository;
|
||||
|
||||
LoginUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<UserEntity> call(LoginParams params) {
|
||||
return repository.login(
|
||||
params.username,
|
||||
params.password,
|
||||
params.sourceType,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class LoginParams {
|
||||
final String username;
|
||||
final String password;
|
||||
final int sourceType; //1:web; 2:mobile; 3:mini_programs; 4:pc
|
||||
|
||||
LoginParams(this.username, this.password, this.sourceType);
|
||||
}
|
||||
77
lib/features/auth/presentation/bloc/auth_cubit.dart
Normal file
77
lib/features/auth/presentation/bloc/auth_cubit.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart';
|
||||
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.dart';
|
||||
|
||||
import '../../../../core/app/app_cubit.dart';
|
||||
import '../../../../core/network/tcp/tcp_client.dart';
|
||||
import '../../../../core/storage/user_storage.dart';
|
||||
import 'auth_state.dart';
|
||||
|
||||
/// emit做的事情:
|
||||
/// 1.修改状态标志:通过改变类的类型(从 Initial 变成 Authenticated)
|
||||
/// 2.携带数据:把 user 对象塞进了状态里,让外部能拿到
|
||||
/// 3.发送通知:自动触发监听(如 GoRouter 的刷新)。
|
||||
class AuthCubit extends Cubit<AuthState> {
|
||||
final UserStorage storage;
|
||||
final TcpClient tcp;
|
||||
final AppCubit appCubit;
|
||||
final NetMessageDispatcher dispatcher;
|
||||
StreamSubscription? _kickOutSub; // 新增:用于管理监听生命周期
|
||||
|
||||
AuthCubit(this.storage, this.tcp, this.appCubit, this.dispatcher)
|
||||
: super(AuthInitial()) {
|
||||
// Cubit 一启动就开始监听 TCP 的“自动逻辑”
|
||||
_listenToAuthResponse();
|
||||
}
|
||||
|
||||
/// App 启动时检查本地缓存
|
||||
Future<void> appStarted() async {
|
||||
final user = await storage.getUser();
|
||||
if (user != null) {
|
||||
// 1. 建立 TCP 连接 (远程控制)
|
||||
tcp.connect(host: TCPConsts.TCP_IP, port: TCPConsts.TCP_PORT);
|
||||
// 2. 同步全局 App 状态
|
||||
appCubit.setAuth(user);
|
||||
// 3. 进入已登录状态
|
||||
emit(AuthAuthenticated(user));
|
||||
} else {
|
||||
emit(AuthUnauthenticated());
|
||||
}
|
||||
}
|
||||
|
||||
/// 当 HTTP 登录/注册成功后调用
|
||||
Future<void> loginSuccess(UserEntity user) async {
|
||||
await storage.saveUser(user);
|
||||
tcp.connect(host: TCPConsts.TCP_IP, port: TCPConsts.TCP_PORT);
|
||||
appCubit.setAuth(user);
|
||||
emit(AuthAuthenticated(user));
|
||||
}
|
||||
|
||||
/// 退出登录 (主动或被动)
|
||||
Future<void> logout() async {
|
||||
await storage.deleteUser();
|
||||
tcp.disconnect();
|
||||
appCubit.clearAuth();
|
||||
emit(AuthUnauthenticated());
|
||||
}
|
||||
|
||||
/// TCP 指令监听
|
||||
void _listenToAuthResponse() {
|
||||
_kickOutSub?.cancel(); // 防止重复监听
|
||||
|
||||
// 假设 0x12 是踢下线或多设备登录提醒
|
||||
_kickOutSub = dispatcher.onJsonMessage(0x12).listen((json) {
|
||||
// 如果后端发来指令确认需要退出
|
||||
logout();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_kickOutSub?.cancel(); // 销毁 Cubit 时关闭监听
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
12
lib/features/auth/presentation/bloc/auth_state.dart
Normal file
12
lib/features/auth/presentation/bloc/auth_state.dart
Normal file
@@ -0,0 +1,12 @@
|
||||
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
|
||||
|
||||
abstract class AuthState {}
|
||||
|
||||
class AuthInitial extends AuthState {}
|
||||
|
||||
class AuthAuthenticated extends AuthState {
|
||||
final UserEntity user;
|
||||
AuthAuthenticated(this.user);
|
||||
}
|
||||
|
||||
class AuthUnauthenticated extends AuthState {}
|
||||
24
lib/features/auth/presentation/bloc/login_bloc.dart
Normal file
24
lib/features/auth/presentation/bloc/login_bloc.dart
Normal file
@@ -0,0 +1,24 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../domain/usecases/login_usecase.dart';
|
||||
import 'login_event.dart';
|
||||
import 'login_state.dart';
|
||||
|
||||
class LoginBloc extends Bloc<LoginEvent, LoginState> {
|
||||
final LoginUseCase loginUseCase;
|
||||
|
||||
LoginBloc(this.loginUseCase) : super(LoginInitial()) {
|
||||
on<LoginSubmitted>((event, emit) async {
|
||||
emit(LoginLoading());
|
||||
try {
|
||||
final user = await loginUseCase(
|
||||
LoginParams(event.username, event.password, event.sourceType),
|
||||
);
|
||||
print('✅ Got user: $user');
|
||||
emit(LoginSuccess(user));
|
||||
} catch (e) {
|
||||
emit(LoginFailure(e.toString()));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
29
lib/features/auth/presentation/bloc/login_cubit.dart
Normal file
29
lib/features/auth/presentation/bloc/login_cubit.dart
Normal file
@@ -0,0 +1,29 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../domain/usecases/login_usecase.dart';
|
||||
import 'auth_cubit.dart';
|
||||
import 'login_state.dart';
|
||||
|
||||
class LoginCubit extends Cubit<LoginState> {
|
||||
final LoginUseCase loginUseCase;
|
||||
final AuthCubit authCubit;
|
||||
|
||||
LoginCubit(this.loginUseCase, this.authCubit) : super(LoginInitial());
|
||||
|
||||
/// Login
|
||||
/// @param username 用户名
|
||||
/// @param password 密码
|
||||
/// @param sourceType 登录来源: 1:web; 2:mobile; 3:mini_programs; 4:pc
|
||||
Future<void> login(String username, String password, sourceType) async {
|
||||
emit(LoginLoading());
|
||||
try {
|
||||
final resultUser = await loginUseCase.call(
|
||||
LoginParams(username, password, sourceType),
|
||||
);
|
||||
authCubit.loginSuccess(resultUser);
|
||||
emit(LoginSuccess(resultUser));
|
||||
} catch (e) {
|
||||
emit(LoginFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
9
lib/features/auth/presentation/bloc/login_event.dart
Normal file
9
lib/features/auth/presentation/bloc/login_event.dart
Normal file
@@ -0,0 +1,9 @@
|
||||
abstract class LoginEvent {}
|
||||
|
||||
class LoginSubmitted extends LoginEvent {
|
||||
final String username;
|
||||
final String password;
|
||||
final int sourceType;
|
||||
|
||||
LoginSubmitted(this.username, this.password, this.sourceType);
|
||||
}
|
||||
17
lib/features/auth/presentation/bloc/login_state.dart
Normal file
17
lib/features/auth/presentation/bloc/login_state.dart
Normal file
@@ -0,0 +1,17 @@
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
|
||||
abstract class LoginState {}
|
||||
|
||||
class LoginInitial extends LoginState {}
|
||||
|
||||
class LoginLoading extends LoginState {}
|
||||
|
||||
class LoginSuccess extends LoginState {
|
||||
final UserEntity user;
|
||||
LoginSuccess(this.user);
|
||||
}
|
||||
|
||||
class LoginFailure extends LoginState {
|
||||
final String message;
|
||||
LoginFailure(this.message);
|
||||
}
|
||||
52
lib/features/auth/presentation/pages/login_page.dart
Normal file
52
lib/features/auth/presentation/pages/login_page.dart
Normal file
@@ -0,0 +1,52 @@
|
||||
import 'package:cc_ui_kit/cc_ui_kit.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../../../core/router/route_paths.dart';
|
||||
import '../bloc/login_cubit.dart';
|
||||
import '../bloc/login_state.dart';
|
||||
|
||||
class LoginPage extends StatelessWidget {
|
||||
final _userCtrl = TextEditingController();
|
||||
final _pwdCtrl = TextEditingController();
|
||||
|
||||
LoginPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Login')),
|
||||
body: BlocListener<LoginCubit, LoginState>(
|
||||
listener: (context, state) {
|
||||
if (state is LoginSuccess) {
|
||||
// Navigator.pushReplacement(
|
||||
// context,
|
||||
// MaterialPageRoute(builder: (_) => HomePage(user: state.user)),
|
||||
// );
|
||||
context.go(RoutePaths.home);
|
||||
}
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
TextField(controller: _userCtrl),
|
||||
TextField(controller: _pwdCtrl, obscureText: true),
|
||||
CCPrimaryButton(
|
||||
onPressed: () {
|
||||
// context.read<LoginBloc>().add(
|
||||
// LoginSubmitted(_userCtrl.text, _pwdCtrl.text),
|
||||
// );
|
||||
context.read<LoginCubit>().login(
|
||||
_userCtrl.text,
|
||||
_pwdCtrl.text,
|
||||
2,
|
||||
);
|
||||
},
|
||||
text: 'Login',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
18
lib/features/home/presentation/pages/home_page.dart
Normal file
18
lib/features/home/presentation/pages/home_page.dart
Normal file
@@ -0,0 +1,18 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/app/app_cubit.dart';
|
||||
import '../../../../core/di/injection.dart';
|
||||
|
||||
class HomePage extends StatelessWidget {
|
||||
// final User user;
|
||||
// const HomePage({super.key, required this.user});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final user = sl<AppCubit>().state.user;
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Home')),
|
||||
body: Center(child: Text('Welcome ${user?.username}')),
|
||||
);
|
||||
}
|
||||
}
|
||||
15
lib/features/register/presentation/pages/register_page.dart
Normal file
15
lib/features/register/presentation/pages/register_page.dart
Normal file
@@ -0,0 +1,15 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class RegisterPage extends StatelessWidget {
|
||||
// final User user;
|
||||
|
||||
const RegisterPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Home')),
|
||||
body: Center(child: Text('Welcome Register')),
|
||||
);
|
||||
}
|
||||
}
|
||||
30
lib/main.dart
Normal file
30
lib/main.dart
Normal file
@@ -0,0 +1,30 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:maibu_satabot_v2/features/auth/presentation/bloc/auth_cubit.dart';
|
||||
|
||||
import 'core/di/injection.dart';
|
||||
import 'features/auth/presentation/bloc/login_bloc.dart';
|
||||
import 'features/auth/presentation/bloc/login_cubit.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await init();
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
sl<AuthCubit>().appStarted();
|
||||
return MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider<LoginBloc>(create: (_) => sl<LoginBloc>()),
|
||||
BlocProvider<LoginCubit>(create: (_) => sl<LoginCubit>()),
|
||||
],
|
||||
child: MaterialApp.router(routerConfig: sl<GoRouter>()),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user