How to Navigate from One Screen to Another in Flutter

Navigation is a very important aspect of mobile apps. Literally, we can’t create useful mobile apps without navigation. In this blog post, let’s check how to navigate between screens in Flutter.

We call full-screen views of a mobile app the screens, but in Flutter, they are called routes. The navigation in Flutter is done by Navigator widget. Navigator considers routes as stack and manages them wisely.

You can easily navigate from one screen to another with the following snippet.

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

And you can navigate back by using the code snippet below.

Navigator.pop(context);

Following is the complete Flutter example for navigating from one screen to another.

import 'package:flutter/material.dart';


void main() => runApp(MyApp());


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: FirstScreen()
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Screen'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('click to navigate'),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondScreen()),
            );
          },
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Screen'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('navigate back'),
          onPressed: () {
            Navigator.pop(
              context
            );
          },
        ),
      ),
    );
  }
}

In this example, I have two routes named FirstScreen and SecondScreen. When the RaisedButton of FirstScreen is pressed it will navigate to SecondScreen whereas pressing the RaisedButton of SecondScreen will navigate back to the former route.

Following is the output of Flutter Example:

flutter navigation

Leave a Comment

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