How to create a custom (ElevatedButton) class constructor with different parameters than its parent class constructor?

Viewed 675

I'm trying to create a custom button class:

import 'package:flutter/material.dart';

class PlayButton extends ElevatedButton {
  PlayButton(
      {required this.buttonText,
      required this.buttonColor,
      required this.onPress});

  final void Function()? onPress;
  final String buttonText;
  final Color buttonColor;

  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPress,
      child: Text(
        buttonText,
        style: TextStyle(fontFamily: 'Verdana'),
      ),
      style: ElevatedButton.styleFrom(
        onPrimary: Colors.white,
        primary: buttonColor,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(50),
        ),
        minimumSize: Size(100, 100),
      ),
    );
  }
}

I get an error message saying The superclass 'ElevatedButton' doesn't have a zero argument constructor.

Try declaring a zero argument constructor in 'ElevatedButton', or explicitly invoking a different constructor in 'ElevatedButton'.

I can write the constructor as something like:

PlayButton(
      {required this.buttonText,
      required this.buttonColor,
      required this.onPress})
      : super(child: Text('a'), onPressed: null);

and remove the error message, but all that's displayed is the default superclass button (with 'a' text). So how can I have a constructor inherit from a parent class while having different parameters than the parent?

2 Answers

It seems you don't need to inherit ElevatedButton at all. Flutter favors composition over inheritance anyway.

Just remove extends ElevatedButton and use extends StatelessWidget and you should be fine.

Pass on the properties of the child class to the parent class as follows:

PlayButton(
      {required this.buttonText,
      required this.buttonColor,
      required this.onPress})
      : super(child: Text(this.buttonText), onPressed: this.onPress);

Hopefully, this should fix the issue.

Related