Navigator in Flutter — one of the most essential tools for navigating between screens.
The Navigator manages a stack of routes (screens/pages). You can:
- Push a new screen onto the stack (navigate forward).
- Pop the current screen off the stack (go back).
- Replace the current screen, or clear the whole stack.
Source Code
//Navigate to a New Screen (Push)
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
},
child: Text('Go to Second Screen'),
)
//Go Back to Previous Screen (Pop)
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Back'),
)
//Replace Current Screen
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => HomeScreen()),
);
Ai Code Analizer
🎨 Important Properties
| Action | Method |
|---|---|
| Go to next screen | Navigator.push() |
| Go back | Navigator.pop() |
| Replace current screen | Navigator.pushReplacement() |
| Clear all & navigate | Navigator.pushAndRemoveUntil() |
| Use route name | Navigator.pushNamed() |
