To my knowledge, I should be able to use EnvironmentObject to observe & access model data from any view in the hierarchy. I have a view like this, where I display a list from an array that's in LinkListStore. When I open AddListView and add an item, it correctly refreshes the ListsView with the added item. However, if I use a PresentationButton to present, I have to do AddListView().environmentObject(listStore), otherwise there will be a crash when showing AddListView. Is my basic assumption correct (and this is behavior is most likely a bug) or am I misunderstanding the use of EnvironmentObject?
Basically: @State to bind a variable to a view in the same View (e.g. $text to TextField), @ObjectBinding/BindableObject to bind variables to other Views, and EnvironmentObject to do the same as @ObjectBinding but without passing the store object every time. With this I should be able to add new items to an array from multiple views and still refresh the Lists View correctly? Otherwise I don't get the difference between ObjectBinding and EnvironmentObject.
struct ListsView : View {
@EnvironmentObject var listStore: LinkListStore
var body: some View {
NavigationView {
List {
NavigationButton(destination: AddListView()) {
HStack {
Image(systemName: "plus.circle.fill")
.imageScale(.large)
Text("New list")
}
}
ForEach(listStore.lists) { list in
HStack {
Image(systemName: "heart.circle.fill")
.imageScale(.large)
.foregroundColor(.yellow)
Text(list.title)
Spacer()
Text("\(list.linkCount)")
}
}
}.listStyle(.grouped)
}
}
}
#if DEBUG
struct ListsView_Previews : PreviewProvider {
static var previews: some View {
ListsView()
.environmentObject(LinkListStore())
}
}
#endif