toly-flutter / flutter_journey

25 stars 2 forks source link

+ 0007 Dart里三个点 ... 是什么语法? #10

Open toly1994328 opened 5 years ago

toly1994328 commented 5 years ago
main() {
  var isJava=true;
  <String>[
    if (isJava) "Java" else "NO java",//dart2.3+ 数组元素内可进行if判断
    "Dart",
    "Swift",
    ...["Kotlin", "python"]//将一个数组中的元素进行解构成一个个元素
  ];
}
skipmaple commented 4 years ago

dart三个点(...)操作符用法

考虑下面一种情况,现在有三个Text Widgets List:

List<Widget> northAmericanCountries = [
  Text('USA'),
  Text('Canada'),
];

List<Widget> asianCountries = [
  Text('India'),
  Text('China'),
];

List<Widget> europeanCountries = [
  Text('France'),
  Text('Germany'),
  Text('Italy'),
];

如果我们把三个List添加到一个Row Widget里,通常需要这么做:

Row(
  children: northAmericanCountries
            ..addAll(asianCountries)
            ..addAll(europeanCountries),
)

现在有个需求是要把asianCountries放在northAmericanCountries前面, 你需要这么去改:

Row(
  children: asianCountries
            ..addAll(northAmericanCountries)
            ..addAll(europeanCountries),
)

你需要重新排列addAll方法的顺序,这非常不方便。

那么,我们的...操作符来了!通过它你可以轻松实现以上操作:

Row(
  children: [
              ...northAmericanCountries,
              ...asianCountries,
              ...europeanCountries
            ],
)

重新排序需要做的操作:

Row(
  children: [
              ...asianCountries,
              ...northAmericanCountries,
              ...europeanCountries
            ],
)