Flutter开发中如何将Stream<Foo?>过滤空值后转换为Stream<Foo>类型
解决方案
方案1:直接使用内置方法组合实现
Dart 空安全环境下,可以通过where过滤空值后调用cast做类型转换,修改后的完整代码如下:
Stream<Foo> get getStream { return _eventChannel .receiveBroadcastStream() .map<Foo?>((dynamic status) { assert( status is int, 'status should be int, but it is ${status.runtimeType}', ); if (status is int) { return FooStatus.valueOf(status); // can be null } return null; // 显式返回null,避免隐式返回的编译警告 }) .where((Foo? value) => value != null) // 过滤所有null值 .cast<Foo>(); // 转换为非空Stream类型 }
方案2:封装扩展方法实现你示例中的链式调用效果
如果你想要和示例中helpMeFiltredLikeThis一致的调用风格,可以给Stream扩展非空过滤方法:
// 定义扩展方法 extension NonNullStreamExt<T> on Stream<T?> { Stream<T> whereNotNull() { return where((T? value) => value != null).cast<T>(); } }
调用时直接使用扩展方法即可:
Stream<Foo> get getStream { return _eventChannel .receiveBroadcastStream() .map<Foo?>((dynamic status) { assert( status is int, 'status should be int, but it is ${status.runtimeType}', ); if (status is int) { return FooStatus.valueOf(status); } return null; }) .whereNotNull(); // 直接返回Stream<Foo>类型 }
注意事项
- 原map逻辑缺少else分支的返回值,Dart会默认隐式返回null,建议显式添加
return null避免编译警告 cast转换是安全的,因为前置where逻辑已经确保流中不会出现null值,不会抛出类型转换异常
内容的提问来源于stack exchange,提问作者EvGeniy Ilyin
相关产品推荐
相关产品推荐

