[英]How to reuse widget styles properly in flutter?
来自前端webframeworks(例如angular,react和vue),我正在努力寻找编写可重用小部件样式的最佳方法。 让我用一个例子来说明这个问题。
可以说我们有这个小部件:
Container(
width: 25,
height: 10,
decoration: BoxDecoration(
color: const Color(0xff7c94b6),
border: Border.all(
color: Colors.black,
width: 8.0,
),
),
child: /* some custom widget */,
);
现在让我说我想使Container
属性(如width
, height
等)可以通过参数更改。 如果未传递属性的某个参数,则应使用其默认值,如下所示:
class CustomWidget extends StatelessWidget {
final double width;
final double height;
final BoxDecoration decoration;
const CustomWidget ({
Key key,
this.width = 25,
this.height = 10,
this.decoration = /* default decoration */
/* possibly even more properties */
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: width,
height: height,
decoration: decoration,
child: /* some custom widget */
}
}
显然,可能会有更多的特性会导致越来越多的样板。 另外,如果该容器默认没有装饰,该怎么办? 您是否应该始终通过自定义容器? 还应考虑将Container嵌套在小部件树的下方。
必须有一个好的解决方案,我想不出来,可能是因为我的想法因前端开发的经验而有偏差。 在Web项目中,您只需传递组件/小部件自定义css-class即可覆盖样式(例如,参数containerClasses
)。 您如何在颤动中正确执行操作?
编辑:本质上我的问题是:扑扑中有一个CSS类吗? 或者:什么是使自定义小部件样式完全可通过参数自定义的最佳方法? 我觉得我必须用手书写每个属性。
在react中,您具有所有html元素(例如div
, input
等)及其道具的接口(例如,对于input
-element,您具有具有value
, class
, type
等的接口),可用于定义哪些参数可以通过自定义组件/小部件。
Flutter样式的行为与Vue范围内的样式化/ React“ styled-component”或React Native一般类似:
在这些情况下,没有“全局样式”。 相反,您可以使用合成来获得所需的结果。
从某种意义上说,每个“ CSS类”都有一个StatelessWidget,而不是一个带有许多参数的大型StatelessWidget。
例如,假设我们要将“红色背景+边框半径”划分为可重复使用的样式,那么通常会有两个小部件:
然后,您将可以独立使用它们:
RedBackground(
child: Text('hello world'),
)
或一起:
RedBackground(
child: MyBorder(
child: Text('hello world'),
),
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.