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

67 Views Asked by At

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

There are 2 best solutions below

0
Ignacio Lee On BEST ANSWER

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.

0
Krish Bhanushali On

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.

class CarWrapper<T> {
  final T data;
  final bool isNull;

  CarWrapper(this.data) : isNull = false;

  CarWrapper.nullValue() : data = null, isNull = true;
}

We can later pass Car? as generic.

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

Add a null value here so that constructor of wrapper knows.

streamController.add(CarWrapper(null)); // Adding a null value

Later we can listen it like this.

streamController.stream.listen((data) {
        if (data.isNull) {
          print("Received a null value.");
        } else {
          print("Received data: ${data.data}");
        }
      });