Generics 如何在Dart中生成更通用的isEmpty()函数?

Generics 如何在Dart中生成更通用的isEmpty()函数?,generics,dart,types,dynamic-typing,Generics,Dart,Types,Dynamic Typing,我有以下实用程序函数,用于检查字符串变量是空的还是空的: bool isEmpty(String s){ return (s??'').isEmpty; } 现在我想为Iterables创建一个类似的函数。实现过程非常简单: bool isEmpty(Iterable i){ return (i??[]).isEmpty; } 但是现在我要么给这两个函数取不同的名字,要么把它们合并成一个。这就是我遇到麻烦的地方 我可以使变量动态: bool isEmpty(dynamic x){

我有以下实用程序函数,用于检查
字符串
变量是空的还是空的:

bool isEmpty(String s){
  return (s??'').isEmpty;
}
现在我想为
Iterable
s创建一个类似的函数。实现过程非常简单:

bool isEmpty(Iterable i){
  return (i??[]).isEmpty;
}
但是现在我要么给这两个函数取不同的名字,要么把它们合并成一个。这就是我遇到麻烦的地方

我可以使变量
动态

bool isEmpty(dynamic x){
  if( x is String) return (x??'').isEmpty;
  if( x is Iterable) return (x??[]).isEmpty;
  throw UnimplementedError('isEmpty() is not defined for the type ${x.runtimeType}');
}
但是如果我传递
字符串s=Null
设置s=Null
,那么x的类型将是
Null
。如果将来我想对
Iterable
String
区别对待
null

我可以使函数通用:

bool isEmpty<T>(T x){
  if( T == String) return ((x as String)??'').isEmpty;
  if( T == Iterable) return ((x as Iterable)??[]).isEmpty;
  throw UnimplementedError('isEmpty() is not defined for the type $T');
}
bool是空的(tx){
if(T==String)返回((x为String)?“”);
如果(T==Iterable)返回((x为Iterable)?[])。为空;
throw UnimplementedError($T类型未定义'isEmpty()');
}
但是现在,如果我传递一个
列表
集合
或任何其他属于
Iterable
的子类型,但不是实际的
Iterable
,它将抛出一个异常


如何使一个
isEmpty()
函数与接受
String
Iterable
的两个独立函数完全相同?

您可以进行扩展。例如:

extension StringExt on String {
  bool isNullOrEmpty() => this == null || this.isEmpty;
}

extension IterableExt<T> on Iterable<T> {
  bool isNullOrEmpty() => this == null || this.isEmpty;
}
字符串上的扩展字符串ext{
bool isNullOrEmpty()=>this==null | | this.isEmpty;
}
Iterable上的扩展IterableText{
bool isNullOrEmpty()=>this==null | | this.isEmpty;
}

由于名称冲突(
String.isEmpty,Iterable.isEmpty
),我已将
isEmpty
重命名为
isNullOrEmpty

这有效!我惊讶地看到,在
列表x=null上调用
x.isNullOrEmpty
工作并返回
true
,但确实如此。