Main

firebase 초기화 중 Splash()를 먼저 보여주고 AuthController에서 로그인 상태에 따라 페이지 이동

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await initialization.then((value) {
    Get.put(AuthController());
  });
  runApp(App());
}

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      home: Splash(),
    );
  }
}

class Splash extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: CircularProgressIndicator()),
    );
  }
}

 

AuthController

onReady 함수 내에서 로그인 상태를 확인, 그에 따라 페이지 이동

class AuthController extends GetxController {
  static AuthController get to => Get.find();
  Rxn<User> firebaseUser = Rxn<User>();
  Rxn<UserModel> firestoreUser = Rxn<UserModel>();
  RxBool isLoggedIn = false.obs;

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    //run every time auth state changes
    ever(firebaseUser, handleAuthChanged);
    firebaseUser.bindStream(user);
  }

  handleAuthChanged(_firebaseUser) async {
    //get user data from firestore
    if (_firebaseUser?.uid != null) {
      firestoreUser.bindStream(streamFirestoreUser());
    }
    if (_firebaseUser == null) {
      Get.offAll(() => LoginPage());
    } else {
      Get.offAll(() => HomePage());
    }
  }

  //Streams the firestore user from the firestore collection
  Stream<UserModel> streamFirestoreUser() {
    print('streamFirestoreUser()');

    return firebaseFirestore
        .doc('/users/${firebaseUser.value!.uid}')
        .snapshots()
        .map((snapshot) => UserModel.fromMap(snapshot.data()!));
  }

  // Sign out
  Future<void> signOut() {
    return auth.signOut();
  }
}

Git commit

https://github.com/mugon-dev/flutter_firebase_blog/commit/d5a51d681816c3759436585345cbf2d4fc39dab4

 

email, password, username 회원가입, 로그인, 로그아웃 구현 및 클라우드 저장 · mugon-dev/flutter_firebase_blo

Permalink This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. Browse files email, password, username 회원가입, 로그인, 로그아웃 구현 및 클라우드 저장 Loading branch informati

github.com

 

728x90

+ Recent posts