NavigationLink .navigationDestination called multiple times and pushes to new View twice

Viewed 166

I have a searchable list displaying various instances of a certain Data Model which are saved in an array. When tapping on one of the list rows a new view opens displaying some information about the Data Model. For demonstration purposes, the view opening displays a randomly generated Number. This works as expected up to this point.

However, when performing a search displaying multiple items and then performing a second search displaying only a subset of the first items, after tapping on the selected row, the NavigationLink pushes to the new view twice.

This problem is easy to replicate with very little code. Here is my Data Model:

struct DataModel: Identifiable, Hashable {
let id = UUID()
var name: String

init(name: String = "unknown") {
    self.name = name
}

static func == (lhs: DataModel, rhs: DataModel) -> Bool {
    return lhs.id == rhs.id
}

func hash(into hasher: inout Hasher) {
    hasher.combine(id)
}
}

And here is my View:

var allDataModels = [DataModel]()

struct ContentView: View {
@State var searchDataModels = [DataModel]()
@State var searchText = ""

let numbers = Array(1...10)

var body: some View {
    NavigationStack {
        List {
            ForEach(searchDataModels, id: \.id) { model in
                NavigationLink(value: model, label: {
                    Text(model.name)
                })
            }
        }.searchable(text: $searchText)

            .onChange(of: searchText, perform: { _ in
                updateSearch()
            })
            
            .navigationDestination(for: DataModel.self, destination: { _ in
                Text("\(Int.random(in: 1...100))")})
    }.onAppear {
        for i in 0...9 {
            allDataModels.append(DataModel(name: "Data \(numbers[i])"))
        }
    }
}

func updateSearch() {
    searchDataModels = allDataModels.filter( { $0.name.localizedCaseInsensitiveContains(searchText) } )
}
}

The following video demonstrates the NavigationLink pushing to two Views after performing two searches. As is visible in the video, the numbers on the screen change, making the views easy to distinguish from one another.

Problem visualization

This Problem has been tested and occurs in iOS 16 beta 3 and persists in beta 4. Earlier versions were not tested (NavigationStack and .navigationDestination(for: , destination:) are new in iOS 16).

1 Answers

The problem seems to be resolved in iOS 16 beta 5.

Related