I’m having an issue with SwiftUI where a @State value doesn’t update in time when displayed in a sheet. Here’s my code:
import SwiftUI
struct ContentView: View {
@State private var value: String? = nil
@State private var showSheet = false
var body: some View {
Button("Initialize Value") {
value = "Hello, World!"
showSheet.toggle()
}
.sheet(isPresented: $showSheet) {
if let value {
Text(value)
} else {
Text("Value is nil.")
}
}
}
}
When I press the "Initialize Value" button, the sheet opens, but the value shows as "Value is nil" instead of the expected "Hello, World!". The value seems to update, but the sheet content doesn’t reflect it immediately.
I confirmed the value is set before showSheet is toggled, and I tried wrapping the content inside onAppear but still faced the issue.
Why does the sheet not see the updated @State value immediately?
What’s the best way to ensure the sheet always shows the updated value?
I would appreciate any guidance on what I might be missing or alternative approaches to fix this issue.
.sheet(item: $value) { value inand delete the bool state..sheet(item: $...)was not available. This post situation is exactly why.sheet(item: $...)was created. See the docs at sheet , "Presents a sheet using the given item as a data source for the sheet’s content."