Flutter: Moving between Screens (beginner guide)

Updated: February 10, 2023 By: A Goodman Post a comment

In Flutter, a screen (page, route) is a normal widget but it’s loaded such that it fills the entire (or the majority) of the device screen. To navigate from one screen to another, we can use Navigator.push(). To go back, we use Navigator.pop().

Example

Preview

We’ll build a tiny Flutter app that has only 2 screens: HomeScreen() and SettingScreen(). Each screen is simple and just contains a button and an AppBar.

The Code

Navigate from the Home screen to the Setting screen:

Navigator.push(
   context, 
   MaterialPageRoute(builder: (_) => const SettingScreen())
);

Go back to the Home screen from the Setting screen:

Navigator.of(context).pop();

Complete code in main.dart:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      // hide the debug banner
      debugShowCheckedModeBanner: false,
      title: "Kindacode.com",
      home: HomeScreen(),
    );
  }
}

// Home Screen
class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Home'),
        ),
        body: Center(
            child: ElevatedButton(
          child: const Text('Go To Setting Screen'),

          // Navigate to the Setting screen
          onPressed: () {
            Navigator.push(context,
                MaterialPageRoute(builder: (_) => const SettingScreen()));
          },
        )));
  }
}

// Setting Screen
class SettingScreen extends StatelessWidget {
  const SettingScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Setting'),
      ),
      body: Center(
        child: TextButton(
          child: const Text('Go Back'),
          // Go back to the Home screen
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ),
    );
  }
}

Hope this helps. Further reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles