I have a custom AppBar that has a function which should handle the OnBackPressed of the screen, but unfortunately is not being triggered and dunno why.
Basically I want that on pressing the back button, to leave the current screen.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: ComponentAppBar(
showGoBackButton: true,
onGoBackPressed: () => Get.back(),
),
body: Container(),
);
}
The custom app bar file:
import 'package:flutter/material.dart';
class ComponentAppBar extends StatefulWidget implements PreferredSizeWidget {
final bool showGoBackButton;
final Function onGoBackPressed;
const ComponentAppBar({
Key? key,
required this.showGoBackButton,
required this.onGoBackPressed,
}) : super(key: key);
@override
_ComponentAppBarState createState() => _ComponentAppBarState();
@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}
class _ComponentAppBarState extends State<ComponentAppBar> {
@override
Widget build(BuildContext context) {
return AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
//
],
),
leading: widget.showGoBackButton
? IconButton(
onPressed: () => widget.onGoBackPressed,
icon: const Icon(
Icons.arrow_back,
color: Colors.black,
),
)
: Container(),
automaticallyImplyLeading: false,
leadingWidth: !widget.showGoBackButton ? 0 : 30,
);
}
}
Pretty straight forward, yet, when pressing the back button nothing happens.
What have I debugged:
- Instead of
Get.back()useNavigator.pop()– same problem - Add an output
onGoBackPressed: () => { print('testing') }– no output - Change
onPressed: () => widget.onGoBackPressedtoonPressed: () => Get.back(), it works - Change
onPressed: () => widget.onGoBackPressedtoonPressed: () => { print('test directly in class') }, it works
Also, when using the F5 debug tools, it shows like this, which is very strange:
>Solution :
It’s all about callbacks.
You’re receiving a callback as argument (onGoBackPressed), and you need to execute it in order for it to work. There are two ways for doing this:
onPressed: widget.onGoBackPressed, //This should work since you're assigning directly onGoBackPressed as the callback to be executed by onPressed
onPressed: ()=>widget.onGoBackPressed.call(), //This should work since you're calling onGoBackPressed callback. In other words, you're executing it. Before, you were just referencing it, without actually executing
Tip: I’d recommend you to avoid dynamics when typing arguments. So, I recommend you to type specifically what your onGoBackPressed callback will return. This way:
final void Function() onGoBackPressed;
Which is the same as
final VoidCallback onGoBackPressed;
Cheers!
