flutter 选择实现可重用按钮的最佳方式

0ejtzxu1  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(129)

我目前正在考虑什么是最好的方法,有一个可重用的按钮,不必重建其小部件,但将有能力传递参数时,我调用它的statefulwidget?
目前,我有基于类的widget...

class DynamicButtonStyle {
  static customButtonStyle({
    String? buttonTitle,
    TextStyle? buttonStyle,
    VoidCallback? onPressedFunction,
  }) {
    return ElevatedButton(
        onPressed: onPressedFunction,
        child: Text(
          buttonTitle ?? '',
          style: buttonStyle ?? const TextStyle(),
        ));
  }
}

这个基于类的小部件,我在一个StatefulWidget中调用它,其中我可以传递一个参数,以便在调用我的Flutter应用程序的每个屏幕页面时可以自定义...
login_page.dart <--//在此statefulwidget文件内部调用...

DynamicButtonStyle.customButtonStyle(
  buttonTitle: "Register now",
  onPressedFunction: testFunction,
),

或者最好只是创建一个StatelessWidget按钮?还是一样的如果最好创建一个StatelessWidget的按钮,我可以在调用它时传递一个参数使其动态(大小,高度,颜色)吗?你能提供一个示例代码吗?谢谢大家。

eulz3vhy

eulz3vhy1#

下面是一个示例,说明如何实现具有可定制属性的无状态按钮小部件:

class MyOutlineButoon extends StatelessWidget {
  const MyOutlineButoon(
      {Key? key,
      required this.text,
      this.margin = const EdgeInsets.symmetric(horizontal: 20),
      this.height = 0,
      this.width = double.infinity,
      this.onPressed,
      this.textColor,
      this.textSize = 13, 
      this.leadingChild, 
      this.trailingChild,
      })
      : super(key: key);
  final EdgeInsetsGeometry margin;
  final double height;
  final double width;
  final void Function()? onPressed;
  final String text;
  final Color? textColor;
  final double textSize;
  final Widget? trailingChild;
  final Widget? leadingChild;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: margin,
      child: OutlinedButton(
        style: ElevatedButton.styleFrom(
            fixedSize: Size(width, height),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12))),
        onPressed: onPressed,
        child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
         Padding(
           padding: EdgeInsets.only(right: leadingChild == null ? 0.0 : 10),
           child: leadingChild,
         ),
          Text(text,
              style: GoogleFonts.dmMono(
                  color: textColor ?? UIColorConstant.nativeGrey,
                  fontSize: textSize)),
                  trailingChild ?? const SizedBox.shrink(),
        ]),
      ),
    );
  }
}

这是我如何使用它的例子:

MyOutlineButoon(
                  width: double.infinity,
                  height: 45,
                  margin: const EdgeInsets.symmetric(horizontal: 20),
                  text: "Sign in with google",
                  leadingChild: 
                   Image.asset(UIAssetConstants.googleButtonImage),
                  onPressed: () async {
                    await context.read<SignUpCubit>().loginWithGoogle();
                  },
                )

相关问题