如何创建可灵活配置原类所有参数的自定义Class实例?
如何创建可定制参数的自定义Flushbar实例
我们以第三方包中的Flushbar类为例,常规创建自定义实例时可直接配置各类参数,示例代码如下:
Flushbar errorFlushBar = Flushbar( title: "Deleted", duration: Duration(seconds: 3), reverseAnimationCurve: Curves.easeOutCirc, backgroundColor: const Color(0xFFFF2727), onPressed: () {}, flushbarStyle: FlushbarStyle.FLOATING, margin: EdgeInsets.all(6.0), borderRadius: SmoothBorderRadius( cornerRadius: 12, cornerSmoothing: 0.7, ), );
将这个实例加入组件树时,直接调用show()方法即可:
errorFlushBar.show()
但如果想定义一个预设基础样式的自定义Flushbar,同时还能在使用时通过原类参数灵活定制,直接写死实例的方式就行不通——比如下面这种写法,所有参数都会被固定,无法在调用时修改:
class MyCustomFlushBarsClass { Flushbar myFlushBar = Flushbar( duration: Duration(seconds: 3), reverseAnimationCurve: Curves.easeOutCirc, backgroundColor: const Color(0xFFFF2727), onPressed: () {}, flushbarStyle: FlushbarStyle.FLOATING, margin: EdgeInsets.all(6.0), borderRadius: SmoothBorderRadius( cornerRadius: 12, cornerSmoothing: 0.7, ), ); }
我们期望实现的效果是,在组件中可以像这样调用,同时能按需定制参数:
// 在某个组件中... myFlushBar(title: "Some String", backgroundColor: Colors.white).show()
解决方案:创建带可选参数的工厂方法或构造函数
要实现这个需求,你可以在自定义类中创建工厂方法,或者直接定义可接收可选参数的构造函数,在内部先应用预设的基础样式,再用传入的参数覆盖对应配置:
方法1:使用工厂方法
class MyCustomFlushbars { // 工厂方法,接收可选参数,返回配置好的Flushbar实例 static Flushbar custom({ String? title, String? message, Duration? duration, Color? backgroundColor, VoidCallback? onPressed, // 可根据需要添加更多Flushbar支持的参数 }) { // 预设基础样式,传入的参数会覆盖默认值 return Flushbar( title: title ?? "默认标题", duration: duration ?? Duration(seconds: 3), reverseAnimationCurve: Curves.easeOutCirc, backgroundColor: backgroundColor ?? const Color(0xFFFF2727), onPressed: onPressed ?? () {}, flushbarStyle: FlushbarStyle.FLOATING, margin: EdgeInsets.all(6.0), borderRadius: SmoothBorderRadius( cornerRadius: 12, cornerSmoothing: 0.7, ), ); } }
调用方式:
// 在组件中使用,按需传参覆盖预设样式 MyCustomFlushbars.custom( title: "自定义标题", backgroundColor: Colors.blue, duration: Duration(seconds: 5), ).show();
方法2:继承Flushbar并扩展构造函数
如果需要更贴近原生Flushbar的使用体验,可以直接继承Flushbar,定义自己的构造函数并初始化预设参数:
class CustomFlushbar extends Flushbar { CustomFlushbar({ super.key, String? title, super.message, Duration? duration, Color? backgroundColor, super.onPressed, // 其他需要暴露的参数 }) : super( title: title ?? "默认标题", duration: duration ?? Duration(seconds: 3), reverseAnimationCurve: Curves.easeOutCirc, backgroundColor: backgroundColor ?? const Color(0xFFFF2727), flushbarStyle: FlushbarStyle.FLOATING, margin: EdgeInsets.all(6.0), borderRadius: SmoothBorderRadius( cornerRadius: 12, cornerSmoothing: 0.7, ), ); }
调用方式:
// 直接像原生Flushbar一样使用,同时保留预设样式 CustomFlushbar( title: "自定义标题", backgroundColor: Colors.green, ).show();
这两种方式都能实现「预设基础样式 + 调用时灵活定制参数」的需求,可根据代码习惯选择合适的方案。
内容的提问来源于stack exchange,提问作者LateBoy
相关产品推荐
相关产品推荐

