Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - how to get @EnvironmentObject data inside @ObservableObject

Tags:

swiftui

Is it possible to use a @EnvironmentObject inside an ObservableObject?

It is giving me an error:

Fatal error: No ObservableObject of type EntryViewModel found. A View.environmentObject(_:) for EntryViewModel may be missing as an ancestor of this view.: file SwiftUI, line 0

I know the @EnvironmentObject is good because I use it other places.

If not, how can I get the information?

class ResultsViewModel: ObservableObject {
    @EnvironmentObject var entry: EntryViewModel
    ...
}

Thank you.

like image 577
diogenes Avatar asked Mar 13 '26 21:03

diogenes


1 Answers

Is it possible to use a @EnvironmentObject inside an ObservableObject?

No, it is not. @EnvironmentObject can be used in View only.

If not, how can I get the information?

A possible solution is to pass it in init:

class ResultsViewModel: ObservableObject {
    var entry: EntryViewModel

    init(entry: EntryViewModel) {
        self.entry = entry
    }
}

Another solution may be to use a singleton or (maybe the best) dependency injection.

like image 160
pawello2222 Avatar answered Mar 15 '26 13:03

pawello2222



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!