When does Navigator create new view instances?

I’m learning to use the Navigator, and when inspecting the API, I noticed there are a couple methods for adding views to the Navigator:


navigator.addView(“nameOfView”, new MainView());

or

navigator.addView(“nameOfView”, this.mainView);

With the latter referencing a concrete object rather than a new instance. However when I tried using the latter method, I found the Navigator created new instances of my view instead of referencing the object I had already created, which was terrible because I was trying to create stateful views for my new application.

Perhaps I’m not understanding all the intended functionality of the Navigator, anyone have any useful input for me?

Thanks!

I think the pattern to use here is to use a class name in the method

public void addView(String viewName, Class<? extends View> viewClass) You would call it with something like

Navigator.addView("mainView", MainView.class); That will let the ClassBasedViewProvider create your views. The views should only be instantiated when you navigate to them, not before, and only once.

You can also write your custom ViewProvider.

Check https://vaadin.com/docs/-/part/framework/advanced/advanced-navigator.html#advanced.navigator.navigating.viewprovider for details .

-Olli

Thank you, I think I got the wrong idea on how it worked. I’ve changed my code to initialize properly after first being navigated to and thing are working fine.

Great to hear you got it working!

-Olli