SwiftUI Data Flow @EnvironmentObject

@EnvironmentObject

Provide shared app-wide state from an ancestor view and consume it with @EnvironmentObject.


Share app-wide state with @EnvironmentObject

Provide a shared object from an ancestor using .environmentObject and consume it in descendants via @EnvironmentObject.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

final class AppSettings: ObservableObject { @Published var theme = "Light" }

struct Root: View {
  @StateObject private var settings = AppSettings()
  var body: some View {
VStack(spacing: 8) {
  Button("Toggle") { settings.theme = (settings.theme == "Light") ? "Dark" : "Light" }
  Child()
}
.environmentObject(settings)
.padding()
} } struct Child: View { @EnvironmentObject var settings: AppSettings var body: some View { Text("Theme: \(settings.theme)") } }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *