dart 使用定制构造函数创建定制UI小部件

pbwdgjma  于 2023-01-22  发布在  其他
关注(0)|答案(2)|浏览(123)

希望在flutter中创建一个基于CupertioButton的自定义按钮。
最终结果应该是这样的:

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

每个“克隆”都应用了它的自定义样式。
这是我一直在折腾的代码,但我不能走得更远:

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

pxy2qtax1#

你不需要为1 StatefulWidget创建2个构造函数,你可以创建一个类,然后创建静态函数,这样就可以返回一个小部件。
示例:

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

rqqzpn5f2#

正确的方法是使用自定义构造函数:

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

最后的结果是:

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

相关问题