In Flutter, a BackButton is a widget that provides a button to navigate back to the previous screen or route. It is typically used in the AppBar
to allow users to navigate back.
Properties:
onPressed
: The callback function to handle the back button press.color
: The color of the back button icon.tooltip
: The tooltip to display when the back button is long-pressed.
AppBar(
leading: BackButton(
onPressed: () {
Navigator.pop(context);
},
color: Colors.white,
),
title: Text("Screen Title"),
)
Where to use BackButton in Flutter
The BackButton
widget in Flutter is typically used in the following scenarios:
- AppBar: As the leading widget, users can navigate back to the previous screen.
- Dialogs: Dialogs provide a way to dismiss the dialog and return to the previous screen.
- Nested Navigation: In nested navigation scenarios, such as when using
Navigator
multiple routes, users can navigate back to the previous route. - Custom Navigation: In custom navigation scenarios, such as when using a custom navigation bar or footer, it provides a way to navigate back to the previous screen.
import 'package:flutter/material.dart';
// Define the BackButtonDemo widget, which is a StatefulWidget
class BackButtonDemo extends StatefulWidget {
// Constructor for the BackButtonDemo widget
const BackButtonDemo({Key? key}) : super(key: key);
@override
State<BackButtonDemo> createState() => _BackButtonDemoState();
}
// State class for BackButtonDemo
class _BackButtonDemoState extends State<BackButtonDemo> {
@override
Widget build(BuildContext context) {
return SafeArea(
// Ensures that the widget is positioned within the safe area of the screen (avoiding notches, status bar, etc.)
child: Scaffold(
// Provides basic material design visual layout structure
appBar: AppBar(
// Title of the AppBar
title: Text(
"Back Button",
style: TextStyle(
color: Colors.white, // Title text color
fontWeight: FontWeight.bold, // Title text weight
),
),
flexibleSpace: Container(
// Custom decoration for the AppBar
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.deepPurple, Colors.orangeAccent], // Gradient colors
begin: Alignment.topLeft, // Gradient start alignment
end: Alignment.topRight, // Gradient end alignment
),
),
),
leading: BackButton(
// BackButton widget to provide a back navigation functionality
color: Colors.white, // Icon color
onPressed: () {
// When the BackButton is pressed, navigate back to the previous screen
Navigator.pop(context);
},
),
),
body: Column(
children: [
// This is where you can add other widgets for the body of the Scaffold
],
),
),
);
}
}