我需要在我的 SignScreen 的 onCreate 方法中呼叫一個函式,但沒有任何適用的地方。我無法currentUserCheck從任何地方呼叫函式。
我嘗試了什么:
init在 viewModel的塊中呼叫它。但問題是它扔nullPointerException在NavController這里。呼叫它,
MainActivity但MyTheme我在這些范圍內遇到了許多奇怪的問題。
視圖模型:
@HiltViewModel
class SignViewModel (@ApplicationContext context: Context) : ViewModel() {
val auth = FirebaseAuth.getInstance()
init {
currentUserCheck(NavController(context))
}
fun signIn(email: String?, password: String?, context: Context, navController: NavController) {
if (email != null && email.isNotBlank() && password != null && password.isNotBlank()) {
auth.signInWithEmailAndPassword(email, password).addOnSuccessListener {
navController.navigate(ScreenHolder.ProfileScreen.route) {
popUpTo(ScreenHolder.SigningScreen.route) {
inclusive = true
}
}
}.addOnFailureListener {
Toast.makeText(context, it.localizedMessage, Toast.LENGTH_LONG).show()
}
} else {
Toast.makeText(
context,
"Lütfen email ve ?ifre alanlar?n? bo? b?rakmay?n?z.",
Toast.LENGTH_LONG
).show()
}
}
fun signUp(email: String?, password: String?, context: Context, navController: NavController) {
if (email != null && email.isNotBlank() && password != null && password.isNotBlank()) {
auth.createUserWithEmailAndPassword(email, password)
.addOnSuccessListener {
navController.navigate(ScreenHolder.ProfileScreen.route) {
popUpTo(ScreenHolder.ProfileScreen.route) {
inclusive = true
}
}
}
} else {
Toast.makeText(
context,
"Lütfen email ve ?ifre alanlar?n? bo? b?rakmay?n?z.",
Toast.LENGTH_LONG
).show()
}
}
fun currentUserCheck(navController: NavController) {
if (auth.currentUser != null) {
navController.navigate(ScreenHolder.ProfileScreen.route) {
popUpTo(ScreenHolder.ProfileScreen.route) {
inclusive = true
}
}
}
}
}
uj5u.com熱心網友回復:
解決方案
正如@Pztar 所說,我將身份驗證控制操作宣告為 viewModel 中的一個狀態,然后我在我的 ComposableSignScreen中使用LaunchEffect觀察它并解決了它。
@HiltViewModel
class SignViewModel (@ApplicationContext context: Context) : ViewModel() {
val auth = FirebaseAuth.getInstance()
var currentUser = mutableStateOf(false)
//New currenUserCheck method that declare if state is true or not
fun currentUserCheck() {
if (auth.currentUser != null) {
currentUser.value = true
}
}
}
@Composable
fun SignScreen(viewModel: SignViewModel= hiltViewModel(),navController: NavController,context: Context) {
//Observing the state from my composable and routing user if state is true.
LaunchedEffect(key1 = Unit ){
viewModel.currentUserCheck()
if (viewModel.currentUser.value){
navController.navigate(ScreenHolder.ProfileScreen.route) {
popUpTo(ScreenHolder.SigningScreen.route) {
inclusive = true
}
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/490333.html
