Home > Software engineering >  Create a custom UI widget with custom constructors
Create a custom UI widget with custom constructors

Time:01-22

Looking to create a custom button in flutter that is based on the CupertioButton.

the end result should be looking like this:

MainCustomButton.success(label: 'ok', onPressed: (){});
MainCustomButton.danger(label: 'delete', onPressed: (){});

with each of the 'clones' have it's custom styles applied.

This is the code I have been messing with but I couldn't go further than this:

class MainCustomButton extends StatefulWidget {
    MainCustomButton.success({
        Key? key,
    }) : super(key: key);

    MainCustomButton.danger({
        Key? key,
    }) : super(key: key);

    @override
    State<MainCustomButton> createState() => _MainCustomButtonState();
}

class _MainCustomButtonState extends State<MainCustomButton> {
    @override
    Widget build(BuildContext context) {
        return CupertinoButton(child: Text('click me'), onPressed: () {});
    }
}

CodePudding user response:

You don't have to create 2 constructors for 1 StatefulWidget. You can create a class and make static functions instead that returns you a widget.

Example:

class MainButton{
  static Widget success({required String label, required VoidCallback ontap}){
  return CupertinoButton(child: Text(label), onPressed: ontap);
 }

 static Widget danger({required String label, required VoidCallback ontap}){
  return CupertinoButton(child: Text(label), onPressed: ontap);
 }
}

CodePudding user response:

The right way to do this is using enter image description here

  • Related