The canvas is giving me an error and the app crashed because of this error:
Fatal error: No ObservableObject of type LocationsViewModel found. A View.environmentObject(_:) for LocationsViewModel may be missing as an ancestor of this view.
Also this is the error from the canvas:
SwiftUI App crashed due to missing environment of type: LocationsViewModel. to resolve this add .environmentObject(LocationsViewModel(...)) to the appropriate preview
Of course that line of code is already there and that error only shows in this swift file alone. other files works peoperly
@main
struct SwiftUI_Map_AppApp: App {
@StateObject private var vm = LocationsViewModel()
var body: some Scene {
WindowGroup {
LocationsView()
.environmentObject(vm) // Any child view will have access to this environment object
}
}
}
LocationsView:
@EnvironmentObject private var vm: LocationsViewModel
var body: some View {
ZStack {
// Content
}
.sheet(item: $vm.sheetLocation) { location in
LocationDetailView(location: location)
}
}
}
struct LocationsView_Previews: PreviewProvider {
static var previews: some View {
LocationsView()
.environmentObject(LocationsViewModel())
}
}
LocationDetailView:
@EnvironmentObject private var vm: LocationsViewModel
let location: Location
var body: some View {
ScrollView {
VStack {
imageSection
.shadow(color: Color.black.opacity(0.3), radius: 20, x: 0, y: 10)
VStack(alignment: .leading, spacing: 16) {
titleSction
Divider()
descriptionSction
Divider()
mapLayer
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
}
}
.ignoresSafeArea()
.background(.ultraThinMaterial)
.overlay(alignment: .leading) {
backButton
}
}
}
struct LocationDetailView_Previews: PreviewProvider {
static var previews: some View {
LocationDetailView(location: LocationsDataService.locations.first!)
.environmentObject(LocationsViewModel()) <- Error here
// as if it's not even there
}
}
LocationsViewModel:
class LocationsViewModel: ObservableObject {
init() {
let locations = LocationsDataService.locations
self.locations = locations
mapLocation = locations.first!
}