Getting an error of "Missing argument for parameter ‘realmManager’ in call" for TasksView()
I tried to read the documentations for Realm but based on the code, I don’t think there is anything wrong? There is something missing but I don’t know what it is.
Code is below:
TasksView File –
import SwiftUI
struct TasksView: View {
@Environment var realmManager: RealmManager
var body: some View {
VStack {
Text("Task List")
.font(.title3).bold()
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(hue: 0.086, saturation: 0.141, brightness: 0.901))
}
}
struct TasksView_Previews: PreviewProvider {
static var previews: some View {
TasksView()
.environmentObject(realmManager)
}
}
ContentView2 File –
import SwiftUI
struct ContentView2: View {
@StateObject var realmManager = RealmManager()
@State private var showAddTaskView = false
var body: some View {
ZStack(alignment: .bottomTrailing){
TasksView()
.environmentObject(realmManager)
SmallAddButton()
.padding()
.onTapGesture {
showAddTaskView.toggle()
}
}
.sheet(isPresented: $showAddTaskView) {
AddTaskView()
.environmentObject(realmManager)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
.background(Color(hue: 0.086, saturation: 0.141, brightness: 0.901))
}
}
struct ContentView2_Previews: PreviewProvider {
static var previews: some View {
ContentView2()
}
}
2
Answers
@Environment
works with theenvironment
view modifier, and allows you to read a value of a particular key path ofEnvironmentValues
.You are using
environmentObject
to inject the realm manager, since you want to share the realm manager among the views. You should use@EnvironmentObject
to read the values fromenvironmentObject
modifiers, not@Environment
.Declare
realmManager
like this:I believe the issue is in your declaration of
realmManager
inTaskView
. Whenever you pass an@StateObject
to the view hierarchy viaenvironmentObject(_:)
, the way you use that object in a child view is by wrapping a variable with@EnvironmentObject
that has the desired type of object you want to use, not@Environment
. There can only be one environment object per type available, allowing SwiftUI to deduce which object your@EnvironmentObject
is referencing.Example:
@Environment
is used for different purposes and can be read about more here.