Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter Iterable扩展不区分大小写排序_Flutter_Iterable - Fatal编程技术网

Flutter Iterable扩展不区分大小写排序

Flutter Iterable扩展不区分大小写排序,flutter,iterable,Flutter,Iterable,我从SO复制了答案,使用了一个分机进行排序 extension IterableX<E> on Iterable<E> { Iterable<E> sortedBy(Comparable key(E e)) => toList()..sort((a, b) => key(a).compareTo(key(b))); } Iterable上的扩展IterableX{ Iterable sortedBy(可比键(E))=>

我从SO复制了答案,使用了一个分机进行排序

extension IterableX<E> on Iterable<E> {
  Iterable<E> sortedBy(Comparable key(E e)) =>
      toList()..sort((a, b) => key(a).compareTo(key(b)));     
}
Iterable上的扩展IterableX{ Iterable sortedBy(可比键(E))=> toList()…排序((a,b)=>键(a)。比较键(b)); } 我用它来按字母顺序排序,但想使它不区分大小写,我不能

extension IterableX<E> on Iterable<E> {
  Iterable<E> caseInsensitiveSortedBy(Comparable key(E e)) => toList()
    ..sort((a, b) => key(a?.toUpperCase())
        .compareTo(key(b?.toUpperCase())));
}
Iterable上的扩展IterableX{ Iterable case insensitivesortedby(可比键(E))=>toList() …排序((a,b)=>键(a?.toUpperCase()) .compareTo(键(b?.toUpperCase()); } 不允许,因为没有为类型“”定义方法“toUpperCase”。

所以我正在努力

Iterable<E> caseInsensitiveSortedBy(Comparable key(E e)) => toList()
    ..sort((a, b) =>
        key(a is String? ? a.toUpperCase() : a).compareTo(key(b is String? ? b.toUpperCase() : b)));
Iterable caseinsensitiviesortedby(可比键(E))=>toList()
…排序((a,b)=>
键(a是字符串??a.toUpperCase():a)。比较键(键(b是字符串??b.toUpperCase():b));

我得到的
参数类型“Object?”不能分配给参数类型“E”。

您的扩展应仅应用于
,而不是任何Iterable:

Iterable上的扩展IterableX{ Iterable caseInsensitiveSortedBy()=>toList() …排序((a,b)=>a.toUpperCase() .比较(b.toUpperCase()); }

你不能在任何类型上调用
toUpperCase

@pskink我不明白为什么它在类型检查时不起作用,就像第三个选项一样?@user3808307在你的示例中,你正在调用
get
,它需要类型
E
。在执行
.toUpperCase
时,尝试调用
get
的类型从
E
更改为
String
。即使您知道只有当
E
String
时才会调用
toUpperCase
,Dart类型系统也不知道。这就是演员的作用。因此,您也可以使用第三个选项并执行
.toUpperCase()作为E
@user3808307,我选择将扩展限制为仅字符串,部分原因是我没有密切注意您的第三个示例,但主要原因是将
caseinsensitiviesortedby
作为通用扩展没有意义,因为它仅在
string
s上有意义。