Menu
CoddyTech

Go Back With a Button

Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 20 of 33.

The back arrow is not the only way back. A Save or Done button should also close its screen when it is pressed. Navigator.pop takes the top screen off the stack, the same as the back arrow:

ElevatedButton(
  onPressed: () {
    Navigator.pop(context);
  },
  child: const Text('Save'),
)

Push and pop are a pair: push puts a screen on, pop takes it off. Pushing the home screen again would not go back. It would put a second home screen on top of the pile, with a back arrow that leads to the settings.

challenge icon

Challenge

Easy

The Save button on the settings screen does nothing. Make it close the settings screen and go back to the home screen with Navigator.pop.

Try it yourself

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Home')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const SettingsScreen()),
            );
          },
          child: const Text('Open settings'),
        ),
      ),
    );
  }
}

class SettingsScreen extends StatelessWidget {
  const SettingsScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Settings')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {},
          child: const Text('Save'),
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lists and Screens

Practice on your own: Online Flutter compiler