在Bloc架构中,建议将所有不相关的逻辑单元隔离开来,包括身份验证和数据库连接。以下是一些示例代码的建议,可以实现这种分离:
身份验证:
class AuthService {
final FirebaseAuth _firebaseAuth;
AuthService({
FirebaseAuth firebaseAuth,
}) : _firebaseAuth = firebaseAuth ?? FirebaseAuth.instance;
Stream get user => _firebaseAuth.authStateChanges();
Future signInWithEmailAndPassword(String email, String password) async {
try {
final UserCredential userCredential = await _firebaseAuth.signInWithEmailAndPassword(
email: email,
password: password,
);
return userCredential.user;
} on FirebaseAuthException catch (e) {
// handle error
}
}
Future signOut() async {
await _firebaseAuth.signOut();
}
}
class AuthenticationBloc extends Bloc {
final AuthService _authService;
AuthenticationBloc(AuthService authService)
: _authService = authService,
super(const AuthenticationState.unknown()) {
on(_onUserChanged);
}
void _onUserChanged(AuthenticationUserChanged event, Emitter emit) {
emit(AuthenticationState.authenticated(event.user));
}
@override
Future close() {
// clean up resources
return super.close();
}
}
数据库连接:
class FirestoreService {
final FirebaseFirestore _firestore;
FirestoreService({
FirebaseFirestore firestore,
}) : _firestore = firestore ?? FirebaseFirestore.instance;
Stream getCollection({@required String path}) {
return _firestore.collection(path).snapshots();
}
Future setData({@required String path, @required Map data}) async {
await _firestore.doc(path).set(data);
}
Future delete({@required String path}) async {
await _firestore.doc(path).delete();
}
Future getDocument({@required String path}) async {
return _firestore.doc(path).get();
}
Future updateData(
{@required String path, @required Map data}) async {
await _firestore.doc(path).update(data);
}
}