I’m trying to use a custom Widget which uses a function to do a Navigation.pop(). If I use the GestureDetector in the page, the navigation from FirstPage to SecondPage works fine (commented out code). But if I use a separate Widget (MyButton) with a function which should trigger the Navigator.pop(), then the Navigator.push() doesn’t work. There’s no error. Thank for any help.
import 'package:flutter/material.dart';
void main() => runApp(TestNavigation());
class TestNavigation extends StatelessWidget {
const TestNavigation({super.key});
@override Widget build(BuildContext context) {
return const MaterialApp(home: FirstPage());
}
}
class FirstPage extends StatefulWidget {
const FirstPage({super.key});
@override State<FirstPage> createState() => _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
@override Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondPage()));
},
child: const Text(
'Click to next Page',
))));
}
}
class SecondPage extends StatelessWidget {
@override Widget build(BuildContext context) {
return Scaffold(
// body: GestureDetector(
// onTap: () {
// Navigator.pop(context);
// },
// child: Container(
// child: Center(child: Text('Go back to first page')))));
body: MyButton(
onTap: () {
Navigator.pop(context);
},
text: 'Go back to first page'));
}
}
class MyButton extends StatelessWidget {
final String text;
final Function onTap;
const MyButton({required this.text, required this.onTap});
@override Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap(), child: Center(child: Text(text)));
}
}
No navigation is happening. But if I use the commented out code then it works.
3
Answers
onTap is a callback function, declare it as
VoidCallback
.Here’s your custom widget and i tried it and was working:
Hope it helps you.
change the way you’re calling
onTap
from
onTap: onTap()
toonTap: () => onTap(),
here the full code
Mybe you can try this: