swiftuiwidgetkitactivitykit

@Environment holds wrong values when accessed from Widget


I want to create a customised View for when my Live Activity is shown on the SmartStack on Apple Watch. After adding all the necessary modifiers, I tried to read supportedActivityFamilies from within the Widget.

struct MyLiveActivity: Widget {

    @Environment(\.supportedActivityFamilies) private var supportedFamilies

    var body: some WidgetConfiguration {
      // composed the view here
    }
}

It was supposed to show [small, medium], but it always just shows [medium]. No matter what I tried, all the @Environment properties were outdated. Why can't I get the actual Environment?


Solution

  • As per the documentation @Environment retrieves the environment of a View. However I tried to access it from within a Widget, which is why I did not get reliable values.
    To solve the problem, simply extract the content of your Widget into a separate View and call @Environment from there.

    struct MyLiveActivityView: View {
        
        @Environment(\.supportedActivityFamilies) private var supportedFamilies
        
        var body: some View {
          // compose the view
        }
    }
    
    struct MyLiveActivity: Widget {
        
        var body: some WidgetConfiguration {
          // boilerplate code left out for readability
          MyLiveActivityView()
        }
    }