简体   繁体   English

使用自定义构造函数创建自定义 UI 小部件

[英]Create a custom UI widget with custom constructors

Looking to create a custom button in flutter that is based on the CupertioButton .希望在 flutter 中创建一个基于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.每个“克隆”都应用了自定义 styles。

This is the code I have been messing with but I couldn't go further than this:这是我一直在搞乱的代码,但我不能 go 比这更进一步:

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 .您不必为 1 个StatefulWidget创建 2 个构造函数。 You can create a class and make static functions instead that returns you a widget.您可以创建一个 class 并创建 static 函数,而不是返回一个小部件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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