giải pháp với mở rộng phương pháp phù hợp tốt để đáp ứng trường hợp này:
expect(ListTools.getFlatList([[1],["hello",2],["test"]]),orderedEquals([1,"hello",2,"test"]));
Nhưng không cho luận án những
expect(ListTools.getFlatList([[1],["hello",2,["foo",5]],["test"]]),orderedEquals([1,"hello",2,"foo",5,"test"]));
expect(ListTools.getFlatList([1,["hello",2],"test"]),orderedEquals([1,"hello",2,"test"]));
Để đáp ứng trường hợp thử nghiệm đề tài, bạn cần một cái gì đó đệ quy giống như chức năng sau:
List getFlatList(List list) {
List internalList = new List();
list.forEach((e) {
if (e is List) {
internalList.addAll(getFlatList(e));
} else {
internalList.add(e);
}
});
return internalList;
}
Trân trọng,
Sébastien
Nice! Tôi nghĩ ai đó nên tạo danh sách các thủ thuật phổ biến trong Dart. –
Công thức tuyệt vời cho @shailentuli để thêm. –
Để xử lý nhiều cấp độ lồng nhau hơn, tôi làm điều này: Làm phẳng có thể lặp lại (Iterable iterable) => iterable.expand ((e) => e là Danh sách? Flatten (e): [e]); –