I want to add a null value to a stream, but it will show an error.
When I do:
final StreamController<Car?> streamController = StreamController<Car?>.broadcast();
streamController.add(null)
I’ll get
flutter: ┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
flutter: │ #0 _BroadcastStreamController.add (dart:async/broadcast_stream_controller.dart:242:14)
flutter: │ #1 CarService.selectCar (package:app/services/car_service.dart:109:39)
flutter: ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
flutter: │ ⛔ type 'Null' is not a subtype of type 'Car' of 'data'
flutter: └─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
This seems like a generic type limit.
Do we have some way do this?
And if we cannot do this to a stream, can we do something like:
class NullCar extends Car {
NullCar();
}
var car = NullCar();
streamController.add(car);
And make the condition car == null
equal true?
2
Answers
Finally, I found that I made a mistake in creating the streamController.
Instead of
I missed typing to
And this is legal to assign a non-nullable instance to a nullable variable.
So my ide thought the streamController accepts null but it's not.
You can use any dummy object or we call it a sentinel value, an indicator of your choice. Your way is also correct but you wont be able to put
car==null check.
But We can also do is create a generic wrapper.
We can later pass Car? as generic.
Add a null value here so that constructor of wrapper knows.
streamController.add(CarWrapper(null));
// Adding a null valueLater we can listen it like this.