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")
})
}
}
Post
Replies
Boosts
Views
Activity
I do really think the container is not correctly initiated yet at that point? Initializing the container prior to passing it in seems to fix it, like so:
@main
struct MyApp: App {
let modelContainer: ModelContainer
init() {
do {
modelContainer = try ModelContainer(for: Item.self)
} catch {
fatalError("Could not initialize ModelContainer")
}
}
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(modelContainer)
}
}
Of course the title should be NOT filled in... sorry.