SwiftData/ModelContainer.swift:159: Fatal error: failed to find a currently active container for Task
Failed to find any currently loaded container for Task)
コンテナを渡す前に初期化すると問題が解決されるようです。
@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)
}
}
struct ContentView: View {
@State private var container = ModelContainer(...)
var body: some Scene {
RecipesList()
.modelContainer(container)
}
}
それ以下では @Environmentを使って問題なく利用できると思っていましたが。
struct RecipesList: View {
@Environment(\.modelContext) private var modelContext
The environment’s modelContext property will be assigned a new context associated with this container. All implicit model context operations in this view, such as Query properties, will use the environment’s context.