Home > front end >  How to extend TextButton?
How to extend TextButton?

Time:09-22

I want to extend TextButton, the codes likes below:

class KMTextButton extends TextButton {
  const KMTextButton({
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ButtonStyle? style,
    FocusNode? focusNode,
    bool autofocus = false,
    Clip clipBehavior = Clip.none,
    required Widget child,
  }) : super(
    key: key,
    onPressed: (){
      print('onPressedFuncInvoked');
      if (onPressed != null) {
        onPressed();
      }
    },
    onLongPress: onLongPress,
    style: style,
    focusNode: focusNode,
    autofocus: autofocus,
    clipBehavior: clipBehavior,
    child: child,
  );

}

Then I will get an error invalid constant value, so how can I do it?

CodePudding user response:

remove const keyword from your code. like this

class KMTextButton extends TextButton {
   KMTextButton({
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ButtonStyle? style,
    FocusNode? focusNode,
    bool autofocus = false,
    Clip clipBehavior = Clip.none,
    required Widget child,
  }) : super(
    key: key,
    onPressed: (){
      print('onPressedFuncInvoked');
      if (onPressed != null) {
        onPressed();
      }
    },
    onLongPress: onLongPress,
    style: style,
    focusNode: focusNode,
    autofocus: autofocus,
    clipBehavior: clipBehavior,
    child: child,
  );

}

CodePudding user response:

You are calling a non-const super because onPressed will be evaluated at runtime. So you either want to remove the const keyword from your custom button class constructor or you just pass the onPressed callback as it is to super(onPressed:onPressed) as I think the if statement you have right now is an unnecessary logic.

It also seems what you are doing is redundant. If you are looking to create a customized version of TextButton, it is better if you composite this as a new widget like so:

class CustomTextButton extends StatelessWidget {

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

  //Add more fields as desired
  final Widget child;
  final VoidCallback? onPressed;

  @override
  Widget build(BuildContext context) {

    //Customize your button
    return TextButton(onPressed: onPressed, child: child);
  }
}
  • Related