Dart中级联符号(Cascade notation)与.where方法搭配失效问题
为什么Dart中.where()方法没有过滤List里的null元素?
先看你的代码:
void main() { List data = ['asdf', null, 'b']; List bata = data ..add('cc') ..where((item) => item != null); print(bata); }
输出结果是:
[asdf, null, b, cc]
问题原因
核心问题出在级联操作符..的特性:级联调用不会返回当前方法的执行结果,而是始终返回原始对象(也就是这里的data列表)。
where()方法本身会返回一个过滤后的Iterable,但因为你用了..where(...),这个过滤结果被直接丢弃了,bata最终接收的还是经过..add('cc')修改后的原始data列表,自然不会有过滤效果。
解决方法
要实现过滤,你需要把where()返回的Iterable转换成List,同时修正赋值逻辑,以下是两种常用写法:
写法一:拆分操作,先修改原列表再生成过滤后的新列表
void main() { List data = ['asdf', null, 'b']; data.add('cc'); // 先给原列表添加元素 List bata = data.where((item) => item != null).toList(); // 过滤后转成新List print(bata); // 输出: [asdf, b, cc] }
写法二:用括号包裹级联操作,链式完成过滤与转List
void main() { List data = ['asdf', null, 'b']; List bata = (data..add('cc')).where((item) => item != null).toList(); print(bata); // 输出: [asdf, b, cc] }
第二种写法里,括号(data..add('cc'))返回的是修改后的data,后续调用where()得到过滤后的Iterable,再通过toList()转换成新列表赋值给bata,就能得到预期的过滤结果。
内容的提问来源于stack exchange,提问作者Neetigya Chahar
相关产品推荐
相关产品推荐

