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
EasyThe 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'),
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lists and Screens
1Scrolling Lists
A List That ScrollsList TilesLeading and TrailingTap a List TileDividers Between Rows5More Than One Screen
Open a New ScreenThe Back ArrowGo Back With a ButtonSend Data to a ScreenGet a Result Back6Tabs, Drawers and Swipes
Tabs With a Navigation BarFilled Icons for the Open TabA Side DrawerSwipe to DeleteUndo a SwipePractice on your own: Online Flutter compiler