Check your runtime warnings in Xcode. I have seen it tell me the SwiftUI environment variables can only be used in a view.
In my widgets I already have a wrapper view to handle a lot of common things & bootstrap. I have a view "WidgetSetStuff" that sets global variables -- or it could adjust a class object passed in.
struct WidgetEntryView : View
{
...
@Environment(\.widgetFamily) var widgetFamily
@Environment(\.showsWidgetContainerBackground) var showsWidgetContainerBackground
var body: some View
{
...
WidgetSetStuff(
family: widgetFamily,
noMargins: showsWidgetContainerBackground == false,
...
)
...
}
WidgetSetStuff constructor sets some globals use elsewhere and has EmptyView() body.