Search code examples
flutterdarttypeerror

Which type should I use here? What data is this snapshot is capturing?


I am unable to understand which circles data type I should change. This is solved by checking null safety, but any other way to do this

 @override
  Widget build(BuildContext context) => Stack(
        children: [
          StreamBuilder<List<Circle>>(
            initialData: [],
            stream: _circle$.map((event) => event.length > 100
                ? event.getRange(event.length - 100, event.length).toList()
                : event),
            builder: (context, snapshot) {
              final circles = snapshot.data;
              return CustomPaint(
                size: size,
                painter: CirclePainter(circles: circles),
              );
            },
          ),
        ],
      );

Solution

  • The problem is related to Null-Safety not directly to the data type.

    After Null-Safety, every type become has two types, a Nullable Type, which accepts a value or null and marked with a question mark at the end ?, and a Non-Nullable Type which accepts only a value and not null.

    Your problem is that you are trying to pass a Nullable List<Circle>? to a Non-Nullable List<Circle> which is not allowed because the Nullable Type might contain a null value which is not accepted by the Non-Nullable Type while the vice versa is a accepted.

    The solution is to check the value of circles and to make sure it is not null, this approach is called Type Promotion, you can do that by make a loading according to snapshot.connectionState and then use the bang operator ! to till Dart that you are sure the value is not null like the following circles!