How to Handle Navigator in Flutter ? | Navigator in Flutter

flutter researchthinker

In Flutter, the Navigator class is responsible for managing the navigation stack and transitions between different screens or routes within your app. Here’s an overview of how to handle navigation using Navigator:

Define Routes

  Define named routes for each screen in your app using MaterialApp or CupertinoApp. For example:

MaterialApp(
  routes: {
    '/': (context) => HomeScreen(),// here '/' main page
    '/details': (context) => DetailsScreen(),// Here '/details' is another page, when user want to moveto this screen 
    // Add more routes as needed
  },
)

Navigate to a New Screen


To navigate to a new screen, use the Navigator.push() method and specify the route name or a MaterialPageRoute with the desired screen. For example:

Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => DetailsScreen()),
);

Pass Data to the New Screen

   – You can pass data to the new screen by specifying arguments when navigating. For example:

Navigator.pushNamed(
  context,
  '/details',
  arguments: {'id': 123}, // Here we can pass argument in case we require in next screen we can pass in this way
);

In the destination screen, access the passed arguments using ModalRoute.of(context) settings.arguments For example:

class DetailsScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final args = ModalRoute.of(context).settings.arguments as Map<String, dynamic>; // in this way we can reterive data of previous screen
    final id = args['id'];
    // Use the passed data
    return Container();
  }
}

Go Back

To go back to the previous screen, use Navigator.pop(context). This will remove the current screen from the navigation stack. For example:

IconButton(
  icon: Icon(Icons.arrow_back),
  onPressed: () {
    Navigator.pop(context);
  },
)

Navigate with Result

  If you need to navigate to a screen and get a result or value back from it, you can use Navigator.push() with await and async. For example:

final result = await Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => DetailsScreen()),
);
// Handle the result returned from the DetailsScreen

In the destination screen, use Navigator.pop(context, result) to return a result back to the previous screen.

These are the basic steps to handle navigation using Navigator in Flutter. You can also customize the transition animations, handle navigation from nested widgets, or implement more complex navigation patterns using onGenerateRoute and onUnknownRoute callbacks.

Leave a Reply

Your email address will not be published. Required fields are marked *

web_horizontal
About Us ♢ Disclaimer ♢ Privacy Policy ♢ Terms & Conditions ♢ Contact Us

Copyright © 2023 ResearchThinker.com. All rights reserved.