13

I am having a small Issue with initializing a State with Data from an EnvironmentObject.

@EnvironmentObject var settings: Settings
    
@State var localAllowReminders: Bool
    
init() {
    self._localAllowReminders = State(initialValue: settings.allowReminders)
}

Obviously, I get the following Error Message: 'self' used before all stored properties are initialized.

Question: How can I initialize a State with Data out of a EnvironmentObject?

Thanks for your help.

1
  • You're best off not using @EnvironmentObject but rather injecting Settings properly and storing it as @ObservedObject. Commented Jan 15, 2021 at 16:22

1 Answer 1

11

EnvironmentObject is injected after view constructor call, so you have to initialize state to some default and reset it to desired value in top body view onAppear modifier, like

@EnvironmentObject var settings: Settings
@State var localAllowReminders: Bool = false   // << just any default
    
var body: some View {
    VStack {       // << any top view
        // ...
    }
    .onAppear {
       self.localAllowReminders = settings.allowReminders   // << here !!
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

May I know how do you know that EnvironmentObject is injected after view constructor call?
@onthemoon, I am getting error No ObservableObject of type "" found when I am trying to get access to environment object from .onAppear method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.