I'm relatively new to Flutter and have been experimenting with navigation and authentication flows in my app. This exploration has raised a couple of fundamental questions about the best practices for screen transitions, especially when it comes to handling user authentication states.
Instantiating Widgets Directly vs. Using Navigator.push:
In Flutter, I've seen two approaches to navigate to a new screen: directly returning a new widget instance (return MyNewWidget();) and using the Navigator.push(context, MaterialPageRoute(builder: (context) => MyNewWidget()));
method. I'm leaning towards the idea that directly creating a widget might not leverage Navigator's built-in features, such as automatic back button support or the ability to override didPop()
method. Could choosing one method over the other impact the way authentication state changes are managed or affect the navigation structure of the app?
Recommendation on Navigation Approach:
Given the potential differences and limitations between these two navigation approaches, is it advisable to primarily use the Navigator for navigating within a Flutter app? I'm interested in understanding whether there are best practices around maintaining a coherent and manageable navigation stack, especially in scenarios involving state changes, and how to best utilize the Navigator's capabilities.
As someone who's still on the learning curve with both programming and Flutter, I appreciate all the guidance I can get. While these questions might seem basic to more experienced developers, getting a clear understanding of these concepts is crucial for me at this stage.
Thanks in advance for your insights and advice!
After getting more involved with Flutter I want to share what I have learned. The two concepts really aren't all that similar and my questions seems silly now, but maybe it can help another Newbie.
Main difference: State management: Whenever one pushes a page on another and then navigates back, the state of that previous page is preserved. If, however, one instanciates the page and then moves back to the previous one through some custom method, the page is reinstanciated removing the previous state.
Navigator comes with built-in features: As assumed in my question, using the built-in navigation comes with nice perks such as the previously mentioned state preservation, an automatically generated back button etc.
In general: When wanting to navigate within your app... use the navigator.
For a cleaner code consider using named routes and a Route Generator Class.