How to navigate in Flutter

Flutter is a UI development kit created by Google. It is used to create hybrid or cross-platform applications using the Dart programming language.

An app screen is a page that is portrayed to the user. Generally, an application contains lots of such screens, so the question arises: How do we navigate from one screen to another?

It’s pretty simple: we use the Navigator class, which is inbuilt in Flutter SDK.

Navigator class

Navigator is yet another widget available in Flutter that helps to manage different screens in the app using a stack-like format. According to the terminology of Flutter, these screens are referred to as routes when using alongside Navigator. Similar to stack, the Navigator class provides two important methods:

  • push: The push method is used to add another route into the current stack. The newly added screen will be visible to the user.
  • pop: The pop method is used to remove the topmost route from the current stackremember how pop works in the stack!. The next available route in the stack will now be visible to the user.

Code

In this example, the user will be redirected to the next page when the button is clicked. The user can click the button again to come back to the previous page.

We will create two screens, namely main.dart and SecondPage.dart. We will import SecondPage in main.dart and add the route of the second screen in the push method of Navigator.

main.dart

import 'package:flutter/material.dart';
import 'SecondPage.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FirstPage(),
    );
  }
}

class FirstPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Page'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Go To Next Page'),
          color: Colors.blue.shade900,
          textColor: Colors.white,
          onPressed: () {
            Navigator.push(context, MaterialPageRoute(builder: (context) => SecondPage()));
          },
        ),
      ),
    );
  }
}

SecondPage.dart

import 'package:flutter/material.dart';

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Page'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Go To Previous Page'),
          color: Colors.blue.shade900,
          textColor: Colors.white,
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}

Output


You can connect with me on Twitter for any discussion.

Thanks for reading!

Free Resources