有没有一种方法可以指定函数参数并在dart中返回const值



我写了一个扩展函数,在ColumnRow中的每个孩子之间添加SizedBox,在孩子之间添加空间,而不是在每个孩子之间放置SizedBox,对此我没有找到任何其他方法。

Column(
children: [
// widgets
].setSpace(height: 10),
)
Row(
children: [
// widgets
].setSpace(width: 10),
)

所以这里List<Widget> setSpace({double? height, double? width})取孩子之间使用的SizedBox的高度或宽度。但由于高度和宽度不是const,我不能使用const SizedBox。那么,在dart中有什么方法可以说参数和返回类型总是cosnt吗?像const List<Widget> setSpace({const double? height, const double? width})和C/C++一样?

我认为这是不可能的,主要是因为const只能应用于构造函数和字段,而不能应用于泛型函数。也许您可以通过创建自己的小部件来实现这一点,该小部件在其build方法中添加SizedBox,并创建const构造函数。

EDIT:这是我的一段代码,它是一个带有const构造函数的自定义小部件。

class UnlockPage extends StatefulWidget {
final String pcData;
const UnlockPage({Key? key, required this.pcData}) : super(key: key);

@override
Widget build(BuildContext context) {
[...]
}
}

第二版:这是一段在DartPad中测试的代码。我认为没有比这更好的了。

class SpacedColumn extends StatelessWidget {
final double height;
final List<Widget> children;
const SpacedColumn({required this.height, required this.children});
@override
Widget build(BuildContext context) {
var actualChildren = <Widget>[];
for (var child in children) {
actualChildren.add(child);
actualChildren.add(SizedBox(height: height));
}
return Column(
children: actualChildren,
);
}
}

你不能。当你传递一个值时,这个值可能与一个对另一个的调用不同。

请注意,const在Flutter上的含义与在其他语言上的含义不同。

使用Flutter,它向渲染引擎指示小部件或方法始终相同,并且渲染引擎在重建屏幕时不必重建此小部件。

在其他语言中充当const的关键字是final

Dart语言中,const的含义与其他语言不同。如果以后不想更改值,则应使用final

最新更新