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. 在视图层中

相关内容

热门资讯

科普常识!科乐齐齐哈尔麻将开挂... 科普常识!科乐齐齐哈尔麻将开挂功能工具,科乐齐齐哈尔麻将一贯真的是有开挂工具(有辅助挂透视)科乐齐齐...
揭秘关于!海豚大厅透视功能攻略... 揭秘关于!海豚大厅透视功能攻略,海豚大厅一贯是有透视攻略(有辅助挂教学)1、玩家可以在海豚大厅透视最...
传递经验!云烟休闲开挂功能攻略... 传递经验!云烟休闲开挂功能攻略,云烟休闲总是是有开挂攻略(有辅助挂助手)1、进入游戏-大厅左侧-新手...
来一盘!518打牌辅助器功能神... 来一盘!518打牌辅助器功能神器,518打牌本来是真的有辅助器神器(有辅助挂方法)1、518打牌免费...
专业讨论!微乐广东麻将辅助器功... 专业讨论!微乐广东麻将辅助器功能神器,微乐广东麻将切实有辅助器神器(有辅助挂详情)1、微乐广东麻将透...
大家学习交流!火神透视挂功能脚... 大家学习交流!火神透视挂功能脚本,火神都是有透视挂脚本(有辅助挂规律)1、很好的工具软件,可以解锁游...
程序员教你!麻将争霸花牌开挂功... 程序员教你!麻将争霸花牌开挂功能方法,麻将争霸花牌竟然有开挂方法(有辅助挂头条)1、用户打开应用后不...
一分钟了解!神武4辅助功能软件... 一分钟了解!神武4辅助功能软件,神武4确实存在有辅助软件(有辅助挂详情)1、一分钟了解!神武4辅助功...
技术分享!沐沐福建麻将透视功能... 您好,沐沐福建麻将这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...
教学盘点!小巷娱乐透视挂功能教... 教学盘点!小巷娱乐透视挂功能教程,小巷娱乐本来是有透视挂教程(有辅助挂方式)1、首先打开小巷娱乐辅助...