来自 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 类等效的东西?或者:使自定义小部件的样式完全由参数自定义的最佳方法是什么。我觉得我必须手写每一个属性。
在 react 中,您有一个用于所有 html 元素的接口(interface)(例如
div
, input
等)及其 Prop (例如,对于 input
-元素,您有一个与 value
, class
, type
的接口(interface)等),您可以使用它来定义可以传递哪些参数来自定义组件/小部件。
最佳答案
Flutter 样式的行为类似于 Vue 作用域样式/React“样式化组件”或 React Native:
在这些场景中没有“全局风格”。相反,您使用合成来获得所需的结果。
从某种意义上说,每个“CSS 类”都有一个 StatelessWidget,而不是一个带有许多参数的大 StatelessWidget。
例如,假设我们想将“红色背景 + 边框半径”拆分为可重用的样式,那么我们通常会有两个小部件:
然后您可以在其中独立使用它们:
RedBackground(
child: Text('hello world'),
)
或一起:
RedBackground(
child: MyBorder(
child: Text('hello world'),
),
)
关于flutter - 如何在 flutter 中正确重用小部件样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57939186/