我不能理解下面提供的代码中的return语句。
import 'package:flutter/foundation.dart';
import 'package:GreatPlace/models/place.dart';
class GreatPlaces with ChangeNotifier{
List<Place> _items=[];
List<Place> get item{
return[..._items];
}
}发布于 2020-06-18 20:19:41
“...”是扩散运算符。在您的示例中,[]创建一个列表对象,..._items将_items中的所有对象插入到该列表中。
因此,基本上item返回一个与_items具有相同值的列表。
有关扩展运算符和其他Dart 2.3功能的示例,请参阅本文:https://medium.com/flutter-community/whats-new-in-dart-2-3-1a7050e2408d‘
如果您想要创建一个组合其他列表或添加附加值的列表,则此运算符很有意义。
示例:
List<String> items1 = ['a', 'b', 'c'];
List<String> items2 = ['d','e','f'];
List<String> items3 = [...items1, ...items2, '!'];
print(items3);
//[a, b, c, d, e, f, !]发布于 2020-06-18 20:24:35
在Dart中,它被称为Spreading Operator。如果你想连接两个数组,请看下面的代码。
List<int> _itemsOne = [1, 2, 3];
List<int> _itemsTwo = [4, 5, 6];
final _itemsAll = [..._itemsOne, ..._itemsTwo];
print(_itemsAll); // prints [1, 2, 3, 4, 5, 6]您可以问为什么不使用List方法addAll。假设您的一个List是null,如果您添加另一个List,它将崩溃。
List<int> _itemsOne;
List<int> _itemsTwo = [4, 5, 6];
_itemsOne?.addAll(_itemsTwo);但是在扩展运算符中,如果您期望使用数组null,则可以在其前面使用空安全运算符?。
List<int> _itemsOne;
List<int> _itemsTwo = [4, 5, 6];
final _itemsAll = [...?_itemsOne, ..._itemsTwo];
print(_itemsAll); // prints [4, 5, 6]https://stackoverflow.com/questions/62449292
复制相似问题