shodak
shodak

Reputation: 85

Can I pass an @Environment property as a parameter to a subview in order to use two-way bindings on its properties?

I'd like to know if I'm going to run into any problems with code structured like this. I have an @Observable class Foo that I want to use to control a Toggle inside a subview. The main App instantiates Foo and passes it into the environment for all subviews. If I access it as an @Environment property in the subview and try to do isOn: $foo.bar in the toggle, the error says "Cannot find $foo in scope". Is this because Environment properties are not two-way bindable? So here's my solution:

@Observable
class Foo {
    var bar: Bool
}

@main
struct MyApp: App {
   @State var foo = Foo()

   var body: some View {
       ContentView()
           .environment(foo)
    }
}

struct ContentView: View {
    @Environment(Foo.self) private var foo

    var body: some View {
        Subview(foo: foo)
    }
}

struct Subview: View {
    @State var foo: Foo

    var body: some View {
        Toggle("Toggle", isOn: $foo.bar)
    }
}

It seems wrong to be unable to use @Environment properties for two-way bindings, but OK to pass them as state parameters to subviews which do exactly that. Is this solution going to cause bugs?

Upvotes: 0

Views: 25

Answers (0)

Related Questions