Bloc架构:从实用和即兴的身份验证/数据库连接迁移
创始人
2024-12-22 20:00:25
0

在Bloc架构中,建议将所有不相关的逻辑单元隔离开来,包括身份验证和数据库连接。以下是一些示例代码的建议,可以实现这种分离:

身份验证:

  1. 创建一个包含所有身份验证逻辑的类,例如:
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();
  }
}
  1. 在视图层中使用Bloc的方式来使用这个类:
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();
  }
}

数据库连接:

  1. 创建一个包含所有数据库连接逻辑的类,例如:
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);
  }
}
  1. 在视图层中

相关内容

热门资讯

第8分钟了解(微扑克ai代打)... 第8分钟了解(微扑克ai代打)黑科技透明挂辅助代打(透视)解密教程(2026已更新)(哔哩哔哩)相信...
七分钟了解(Wepoke苹果版... 七分钟了解(Wepoke苹果版本)外挂透明挂辅助安装(透视)2025版教程(2024已更新)(哔哩哔...
第五分钟了解(靠谱WPK)外挂... 《第五分钟了解(靠谱WPK)外挂辅助插件安装安装(透视)我来教教你(2021已更新)(哔哩哔哩)》 ...
第1分钟了解(赢之城)软件透明... 第1分钟了解(赢之城)软件透明挂辅助科技(透视)必赢教程(2024已更新)(哔哩哔哩);第1分钟了解...
第6分钟了解(Wepoke透视... 第6分钟了解(Wepoke透视)软件透明挂辅助工具(透视)分享教程(2025已更新)(哔哩哔哩);1...
第八分钟了解(德扑网上设置)软... 第八分钟了解(德扑网上设置)软件透明挂辅助科技(透视)规律教程(2025已更新)(哔哩哔哩),德扑网...
7分钟了解(wepoker)软... 7分钟了解(wepoker)软件透明挂辅助器(透视)wpk教程(2025已更新)(哔哩哔哩);1、完...
第2分钟了解(wpk系统)软件... 第2分钟了解(wpk系统)软件透明挂辅助ai(透视)AI教程(2025已更新)(哔哩哔哩);wpk系...
7分钟了解(德扑之星透明)软件... 【福星临门,好运相随】;7分钟了解(德扑之星透明)软件透明挂辅助神器(透视)科技教程(2025已更新...
第八分钟了解(aapokEr)... 第八分钟了解(aapokEr)外挂透明挂辅助黑科技(透视)透明挂教程(2026已更新)(哔哩哔哩);...