![](/img/trans.png)
[英]Dart correct way to specify generic argument type on callback function
[英]Is there a way to specify function parameters and return value as const in dart?
我寫了一個擴展 function 在Column
或Row
中的每個孩子之間添加SizedBox
以在孩子之間添加空間,而不是在每個孩子之間放置SizedBox
,對此我沒有找到任何其他方法。
Column(
children: [
// widgets
].setSpace(height: 10),
)
Row(
children: [
// widgets
].setSpace(width: 10),
)
所以這里List<Widget> setSpace({double? height, double? width})
采用子級之間使用的SizedBox
的高度或寬度。 但是由於 height 和 width 不是const
我不能使用const SizedBox
。 那么在 dart 中有什么方法可以說參數和返回類型都將始終是成本嗎? 像const List<Widget> setSpace({const double? height, const double? width})
像 C/C++?
我認為這是不可能的,主要是因為const
只能應用於構造函數和字段,而不是泛型函數。 也許您可以通過創建自己的小部件來實現這一點,該小部件在其build
方法中添加SizedBox
,並創建一個const
構造函數。
編輯:這是我的一段帶有const
構造函數的自定義小部件的代碼。
class UnlockPage extends StatefulWidget {
final String pcData;
const UnlockPage({Key? key, required this.pcData}) : super(key: key);
@override
Widget build(BuildContext context) {
[...]
}
}
編輯 2:這是在 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,
);
}
}
在Dart
語言中const
與其他語言中的含義不同。 如果您不想稍后更改這些值,則應該使用final
。
你不能。 當您傳遞一個值時,這個值可能與對其他值的調用不同。
請注意, const
在 Flutter 上的含義與在其他語言上的含義不同。
使用 Flutter 向渲染引擎指示小部件或方法始終相同,並且渲染引擎在重建屏幕時沒有義務重建此 Widget。
在其他語言中充當const
的關鍵字是final
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.