SwiftUI Data Flow @EnvironmentObject
SwiftUI Data Flow @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
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)") }
}
import SwiftUI
struct ContentView: View {
var body: some View { Root() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
The example above shows a shared object from an ancestor using .environmentObject and consume it in descendants via @EnvironmentObject.