Skip to content

Fatal error crash when accessing environment object on initial render inside of WrappingHStack #47

@swestwood

Description

@swestwood

Describe the bug
When a view nested inside of WrappingHStack tries to access an environment object on its initial render, it cannot find it and throws a fatal error. (see example below)

If the nested view waits until after the first render to access the environment object, it works.

In either case for the code below, replacing WrappingHStack with HStack works properly.

To Reproduce
Steps to reproduce the behavior:

  1. Set an environment object outside of the WrappingHStack
  2. Try to access the environment object in a subview of WrappingHStack
  3. Fatal error about the environment object not existing

Expected behavior
Replacing WrappingHStack with HStack gives the expected behavior of being able to access the environment object on initial render instead of crashing.

Context:

  • WrappingHStack version: 2.2.9
  • Model: Simulator iPhone 14 Pro

Additional context
Add any other context about the problem here.

Simplified Example
(adapted from https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views)

class GameSettings: ObservableObject {
    @Published var score = 0
}

struct ScoreView: View {
    @EnvironmentObject var settings: GameSettings
    @State var ready = true  // Set this to true and the code crashes, set it to false to skip the initial render, and it works.

    var body: some View {
        Text("Score: \(ready ? settings.score : -1)")
            .onAppear {
                ready = true
            }
    }
}
struct WrappingHStackBugDemo: View {
    @StateObject var settings = GameSettings()

    var body: some View {
        VStack {
            Button("Increase Score") {
                settings.score += 1
            }
            // Replacing this with a regular HStack works in all cases, including initial render
            WrappingHStack {
                ScoreView()
            }
        }
        .frame(height: 200)
        .environmentObject(settings)
    }
}


struct WrappingHStackBugPreview: PreviewProvider {
    static var previews: some View {
        WrappingHStackBugDemo()
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghelp wantedExtra attention is needed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions