I was trying to test this and am getting the error if I initialize the item in the View. Works fine if I initialize the model in the view's .onAppear.
I am not knowledgeable on this subject, but could it be that the container is not ready yet until the view appears? Or I might be using this wrong to beging with...
Doesn't work:
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@State var item: Item?
init() {
freezer = Item(name: "My Item")
}
var body: some View {
Text(item?.name ?? "No item")
}
}
Works:
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@State var item: Item?
var body: some View {
Text(item?.name ?? "No item")
.onAppear(perform: {
item = Item(name: "Test Item")
})
}
}