9.4 C
New York
Saturday, December 2, 2023

Flutter: Moving between Screens (beginner guide)

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

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

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: TextButton(
          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();
          },
        ),
      ),
    );
  }
}

AdvertisementsHope this helps. Further reading:

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

Advertisements

Related Articles

Latest Articles