SwiftUI Navigation automatically closing/pop - Realm

2.8k Views Asked by At

I'm populating a List with a Realm Result set.

When navigating from this list it opens a new view then automatically closes that view.

Using a struct presents no issue.

Why would the second view automatically close?

I have a screen recording but cant post here.

import SwiftUI
import Combine

struct TestStruct:Identifiable{

    let id = UUID()
    let firstname: String
}

extension TestStruct {
    static func all() -> [TestStruct]{
        return[
            TestStruct(firstname: "Joe"),
            TestStruct(firstname: "Jane"),
            TestStruct(firstname: "Johns")
        ]
    }
}

struct TestListView: View {
    let realmList = Horoscope.getHoroscopes() //Fetches from Realm
    let structList = TestStruct.all()

    var body: some View {
        NavigationView{
            // This owrks
            //            List(structList) { item in
            //                MyItemRow(itemTxt: item.firstname)
            //            }

            //This automatically closes the view
            List(realmList) { item in
                MyItemRow(itemTxt: item.firstname)
            }
            .navigationBarTitle("Charts", displayMode: .automatic)
            .navigationBarItems(trailing: EditButton())
        }
    }
}


struct MyItemRow: View {

    var itemTxt:String

    var body: some View {
        NavigationLink(destination: Text("Test")) {
            Text(itemTxt)
        }
    }
}

struct TestListView_Previews: PreviewProvider {
    static var previews: some View {
        TestListView()
    }
}
3

There are 3 best solutions below

4
On BEST ANSWER

I think the answer can be found here

In short, do not generate the id of the collection on which the ForEach iterates. It would detect a change and navigate back.

Realm object has an auto generated id property with each reference, try replacing it with a consistent id

0
On

Changing NavigationView { content } to NavigationStack { content } did the trick for me

0
On

The following solution worked for me.

The code with an issue (specifying id: \.self is the root cause since it uses the hash calculated from all objects the Stream object consists of, including the data that lies in a subarray).

...
List(streams, id: \.self) { stream in
...

The code with no issues:

...
List(streams, id: \._id) { stream in

// or even List(streams) { stream in
...

The streams is a @ObservedResults(Stream.self) var streams and the object scheme is:

final class Stream: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var _id: ObjectId
    @Persisted var title: String
    @Persisted var subtitle: String?
    
    @Persisted var topics = RealmSwift.List<Topic>()

    // tags, etc.
}

The issue happened when I added new topic at the topics list in the first stack of the navigationView.