Home > database >  OnTap Function doesn't work after changing Button to GestureDetector
OnTap Function doesn't work after changing Button to GestureDetector

Time:05-02

I tried to modify my code to make my button decorated using GestureDetector in Stateful widget, from simple ElevatedButton in Stateless widget. Once button is tapped, onPressed function from an argument should be called. But after modifying my code, onPressed function is not working like Nothing happens whereas the decoration is working. OnTap function seems fired so it's wierd.

Before (Worked):

style: ElevatedButton.styleFrom(padding: EdgeInsets.all(20)),
onPressed: onPressed,
child: Text(
  text,
  style: TextStyle(fontSize: 20),
));

After (Not working):

class ButtonWidget extends StatefulWidget {
  final String text;
  final VoidCallback onPressed;

  const ButtonWidget({Key? key, required this.text, required this.onPressed})
      : super(key: key);

  @override
  State<ButtonWidget> createState() => _ButtonWidgetState();
}

class _ButtonWidgetState extends State<ButtonWidget> {
  bool _isElevated = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _isElevated = !_isElevated; // This works
          widget.onPressed; // This Not work
        });
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 150),
        width: 150,
        height: 60,
        decoration: BoxDecoration(
            color: Colors.grey[300],
            borderRadius: BorderRadius.circular(50),
            boxShadow: _isElevated
                ? [
                    BoxShadow(
                      color: Colors.grey[500]!,
                      offset: const Offset(4, 4),
                      blurRadius: 15,
                      spreadRadius: 1,
                    ),
                    const BoxShadow(
                      color: Colors.white,
                      offset: Offset(4, 4),
                      blurRadius: 15,
                      spreadRadius: 1,
                    )
                  ]
                : null),
        child: Center(child: Text(widget.text)),
      ),
    );

CodePudding user response:

you should execute onPressed callback like this:

...
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _isElevated = !_isElevated;

          widget.onPressed?.call(); // or widget.onPressed();
        });
      },
...
  • Related