Home > other >  How to pass a button to another class and perform action when it's pressed?
How to pass a button to another class and perform action when it's pressed?

Time:05-24

I have a class called ApiWidget which accepts a child, this child is going to be one which has onPressed in it, for example, an ElevatedButton.

I want to show this onPressed type child widget in this class but I want to perform some action when that button is pressed. How can I do that? I think provider is just not suitable here.

In other words, I just want to use the child button (for appearance) but I want to perform the operation in this class only.

class ApiWidget extends StatelessWidget {
  final Widget child;

  ApiWidget(this.child);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {}, // I want to perform some operation here when this child is pressed.
      child: child,
    );
  }
}

CodePudding user response:

You can get onPressed with the dataType Function. Example:

import 'package:flutter/material.dart';

class GradientButtonWidget extends StatelessWidget {
  final String title;
  final VoidCallback onPress;

  GradientButtonWidget({
required this.title,
required this.onPress,
});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
        onPressed: onTap,
        child: FittedBox(
          child: Text(title),
        ),
      );
  }
}

The code you wrote looks like this:

class ApiWidget extends StatelessWidget {
  final Widget child;
  final VoidCallback onPress;

  ApiWidget({
required this.child,
required this.onPress,
});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onPress, //This is how it is called
      child: child,
    );
  }
}

CodePudding user response:

The easiest solution is to wrap your child in AbsorbPointer or IgnorePointer widget. Doing so will ignore the onPressed of your button and you're free to perform the logic within that class.

If you also want to make sure your button receives onPressed event, you can do (child as ElevatedButton).onPressed?.call() in the onTap callback.

GestureDetector(
  onTap: () {
    // Perform your operation...
  },
  child: AbsorbPointer(
    child: child, // Your passed button 
  ),
)
  • Related