Search code examples
flutterdartstreamstreamcontroller

Can we add a null value to a StreamController? (Flutter, Dart)


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?


Solution

  • Finally, I found that I made a mistake in creating the streamController.

    Instead of

    final StreamController<Car?> streamController = StreamController<Car?>.broadcast();
    

    I missed typing to

    final StreamController<Car?> streamController = StreamController<Car>.broadcast();
    

    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.