如何< File>在Dart中对结尾为空对象的List进行排序

sz81bmfz  于 9个月前  发布在  其他
关注(0)|答案(3)|浏览(115)

开始着手Flutter的研究项目,我想知道如何排序文件列表。
实际上,我的程序有一个包含4个初始化文件的列表,如下所示:

List<File> imageFiles = List(4);

字符串
这个初始化实际上意味着我的列表是这样的:[null,null,null,null]
当用户执行操作时,这个列表可以填满。但是,用户可以随时删除文件,这可以给予我们以下情况:[file A, null, null, file d]
我的问题是,当一个删除到达时,如何对列表进行排序,以获得一个空对象总是最后的列表([file A, file D, null, null])。
我已经看了很多主题,但他们从来没有涉及DART。
提前感谢您的帮助。

svmlkihl

svmlkihl1#

您可以使用list.sort((a, b) => a == null ? 1 : 0);对列表进行排序
下面是一个完整的示例,使用String而不是File,您可以在DartPad上运行它

void main() {
  List<String> list = List(4);
  list[0] = "file1";
  list[3] = "file4";

  print("list before sort: $list"); 
  // list before sort: [file1, null, null, file4]

  list.sort((a, b) => a == null ? 1 : 0);

  print("list after sort: $list"); 
  // list after sort: [file1, file4, null, null]

}

字符串
如果业务要求最多有4个文件,我建议创建一个值对象来处理。例如:

class ImageList {
  final _images = List<String>();

  void add(String image) {
    if(_images.length < 4) {
      _images.add(image);
    }
  }

  void removeAt(int index) {
    _images.removeAt(index);
  }

  String get(int index) {
    return _images[index];
  }

  List getAll() {
    return _images;
  }
}


你可以这样运行它:

void main() {
  ImageList imageList = ImageList();
  imageList.add("file1");
  imageList.add("file2");
  imageList.add("file3");
  imageList.add("file4");
  imageList.add("file5"); // won't be add

  print("imagelist: ${imageList.getAll()}");
  // imagelist: [file1, file2, file3, file4]

  imageList.removeAt(2); // remove file3
  print("imagelist: ${imageList.getAll()}");
  // imagelist: [file1, file2, file4]
}


这将使控制更容易。(这个例子再次使用String而不是File

ipakzgxi

ipakzgxi2#

你可以试试这个:Demo (Dartpad)
这个地方最终都是空的。

sortedList.sort((a, b) {
  int result;
  if (a == null) {
    result = 1;
  } else if (b == null) {
    result = -1;
  } else {
    // Ascending Order
    result = a.compareTo(b);
  }
  return result;
})

字符串
你也可以使用这个演示:Demo 2 - Dartpad

bq9c1y66

bq9c1y663#

对于任何感兴趣的人,我对Jorge的答案做了一个扩展函数。

extension ListExtension<E> on List<E> {
  void sortByNullable<K extends Comparable<K>>(K? Function(E element) keyOf) {
    sortByCompare((element) => keyOf(element), (a, b) {
      if (a == null) {
        return 1;
      } else if (b == null) {
        return -1;
      } else {
        return a.compareTo(b);
      }
    });
  }
}

字符串

相关问题