SwiftData/ModelContainer.swift:144: Fatal error: failed to find a currently active container for Student

I am currently following the tutorial from Hacking with swift url: (https://www.hackingwithswift.com/books/ios-swiftui/introduction-to-swiftdata-and-swiftui) to integrate SwiftData into a SwiftUI project. The code generated based on the tutorial is provided below. However, an error occurs upon launching the app: SwiftData/ModelContainer.swift:144: Fatal error: failed to find a currently active container for Student.

I am seeking assistance in resolving this issue.

import SwiftUI
import SwiftData

@Model
class Student {
  var id: UUID
  var name: String

  init(id: UUID, name: String) {
    self.id = id
    self.name = name
  }
}

@main
struct project8App: App {
  
  var body: some Scene {
    WindowGroup {
      VStack {
        ContentView()
      }
    }
    .modelContainer(for: Student.self)
  }
}

struct ContentView: View {
  @Environment(\.modelContext) var modelContext
  @Query var students: [Student]
  
  let allStudents = [
    Student(id: UUID(), name: "John"),
    Student(id: UUID(), name: "Paul"),
    Student(id: UUID(), name: "George"),
    Student(id: UUID(), name: "Ringo"),
  ]
  
  var body: some View {
    VStack {
      ForEach(students) { student in
        Text("\(student.name)")
      }
      Button(action: {
        // random student
        let student = allStudents.randomElement()!
        modelContext.insert(student)
      }) {
        Text("Add/Change name")
      }
    }
  }
}

P.S. It appears that the problem may be related to the container not being initialized by .modelContainer(for: Student.self). I have managed to resolve the error with the modified version below. However, I am still curious about the reasons behind the original version's malfunction and the differences between the two implementations.

// version 2, which is ok to run

@main
struct project8App: App {
  let modelContainer: ModelContainer
  init() {
    do {
      modelContainer = try ModelContainer(for: Student.self)
    } catch {
      fatalError("Could not initialize ModelContainer")
    }
  }
  
  var body: some Scene {
    WindowGroup {
      VStack {
        ContentView()
      }
    }
    .modelContainer(modelContainer)
  }
}

This only happens on the preview right? For a good explanation: https://www.hackingwithswift.com/forums/100-days-of-swiftui/day-54-crash-in-preview-of-swiftdata/26510/27172

TLDR; in the preview you're not initializing the container, so you'll need to:

#Preview { ContentView() .modelContainer(for: Student.self) }

SwiftData/ModelContainer.swift:144: Fatal error: failed to find a currently active container for Student
 
 
Q