sdk
sdk copied to clipboard
False positive unnecessary cast in firstWhere with orElse
Dart version: Dart SDK version: 2.17.6 (stable) (Tue Jul 12 12:54:37 2022 +0200) on "macos_arm64"
The problem is that this code creates unnecessary cast warning:
final RxList<XFile> selectedFiles = <XFile>[].obs;
final XFile? xFile = (selectedFiles as RxList<XFile?>).firstWhere((element) => file.name == element?.name, orElse: () => null);
but when using the suggestion it changes code below which is wrong because it cannot return null from the orElse clause.
final XFile xFile = (selectedFiles).firstWhere((element) => file.name == element?.name, orElse: () => null);
The warning seems unnecessary, but the cast isn't actually working, so some warning is warranted.
You have an RxList<XFile>
, which I assume is not an RxList<XFile?>
(because then you could have written that as the type in the first line.)
The (selectedFiles as RxList<XFile?>)
cast up-casts to the supertype, relying on unsafe covariance to be valid.
However, the firstWhere
method is precisely one which is not safe to use covariantly.
When you do:
final XFile? xFile = (selectedFiles as RxList<XFile?>).firstWhere((element) => file.name == element?.name, orElse: () => null);
you pass a () => null
method as the orElse
argument to an RxList<XFile>
, which is going to cause a run-time error. The function passed as orElse
must return an XFile
, because that's what RxList<XFile>
requires (because it's a List<XFile>
).
The warning you get is not correct (the cast is not unnecessary), but it's correct to give a warning here (the use of the cast value is not safe).