简体   繁体   中英

Why can't I send a struct to the next view modally but works well through Navigationlink (SwiftUI)

So I am creating a basic Firebase registration and log in app using SwiftUI. In the registration page, I create a user and authenticate it via Firebase and the response I get is email address, User UID, fullName.

I then create a User struct out of this and then send the struct to HomeView . Here is how I am doing it:

first I declare this User struct:

@State var user = User()

Then when you tap register button:

    func handleRegisterTapped() {
    if self.password != confirmPassword {
        print("Error - Passwords don't match")
        self.showAlert = true
        return
    }
    
    print(self.email, self.password)
    
    Auth.auth().createUser(withEmail: self.email, password: self.password) { result, error in
        let id = result?.user.uid
        self.user = User(id: id, fullName: self.fullName, email: self.email)
        do {
            let _ = try db.collection("Users").addDocument(from: user)
            self.showHomeScreen = true
        }catch {
            print(error)
        }
        
    }
}

So this code creates a new user using email address and password, and creates a User object and saves that too on the Firestore User collection.

Then it triggers showHomeScreen boolean which triggers a fullScreenCover modal:

.fullScreenCover(isPresented: $showHomeScreen, content: {
        HomeView(user: self.user)
  })

This is the HomeView :

struct HomeView: View {

    @State var user: User
    var body: some View {
        Text("Welcome, \(user.fullName ?? "")")
    }
}

However, the new view doesn't show the fullName, it says "Welcome, " thats it. If I do this same approach with NavigationLink it works all the time. But not with modal view. How do I approach this. Any help will be appreciated. Thanks

you could try passing a binding to HomeView, something like this:

struct HomeView: View {
    @Binding var user: User  // <--- here
    var body: some View {
        Text("Welcome, \(user.fullName ?? "")")
    }
}

and call

.fullScreenCover(isPresented: $showHomeScreen, content: {
        HomeView(user: self.$user)   // <--- here
  })  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM