简体   繁体   中英

Create a custom UI widget with custom constructors

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: () {});
    }
}

The right way to do this is using custom constructors :

class MainCustomButton extends StatelessWidget {
  const MainCustomButton({Key? key, required this.label}) : super(key: key);

  final String label;

  const MainCustomButton.success({super.key, this.label = 'ok'});

  const MainCustomButton.danger({super.key, this.label = 'delete'});

  @override
  Widget build(BuildContext context) {
    return CupertinoButton(
      child: Text(label),
      onPressed: () {},
    );
  }
}

And the final result:

Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisAlignment: MainAxisAlignment.center,
        children: const [
          MainCustomButton.success(),
          MainCustomButton.danger(),
        ],
      ),
    );

在此处输入图像描述

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);
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM