簡體   English   中英

有沒有辦法在 dart 中指定 function 參數和返回值作為 const?

[英]Is there a way to specify function parameters and return value as const in dart?

我寫了一個擴展 function 在ColumnRow中的每個孩子之間添加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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM