【发布时间】:2023-03-15 03:58:01
【问题描述】:
来自 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 */
}
}
显然,可能会有更多的属性导致越来越多的样板。另外,如果容器默认没有装饰,你会怎么做?你应该总是传递一个自定义容器吗?还要考虑容器可以嵌套在小部件树的下方。
一定有好的解决方案,就是想不出来,可能是因为我的前端开发经验,我的想法有偏见。在 web 项目中,您只需传递组件/小部件自定义 css 类来覆盖样式(例如参数containerClasses)。在flutter中如何正确地做到这一点?
编辑:本质上,我的问题是:flutter 中是否有与 css-class 等效的东西?或者:使自定义小部件的样式完全由参数自定义的最佳方法是什么。我觉得我必须手写每一个属性。
在反应中,你有一个用于所有 html 元素的接口(例如div、input 等)及其道具(例如,对于input-元素,你有一个与value、class 的接口, type 等),您可以使用它来定义可以传递哪些参数来自定义组件/小部件。
【问题讨论】:
-
如果你来自 Vue/React,我看不到你不明白的地方。在 Flutter 中重用样式类似于 Vue 中的 scoped styled 或 React 中的 package styled-component。
-
我不明白范围样式如何增强样式的可重用性。我还编辑了我的帖子,以使我的问题更清楚。
标签: flutter dart flutter-layout