Flutter Null-Safety Question: mismatch type issue

Viewed 337

This is my function typedef:

typedef Widget ItemBuilder<T>(T item);

This is my class property:

final ItemBuilder<T>? itemBuilder;

This is how I pass this to my object:

itemBuilder: (Color color) => Container(height: 100.0, color: color)

This is the error that I get:

type '(Color) => Container' is not a subtype of type '((Color?) => Widget)?'

Can you help me figure this out?

1 Answers

The type error here is that the itemBuilder property is of type ItemBuilder<Color?>? while you are passing an instance of ItemBuilder<Color>?.

The difference is subtle, however, you are expecting a non-null Color while the parameter expects a callback expecting a potentially null Color?.


There are two ways to fix this.

Expect non-nullable parameter

If this is possible and intended, you should adjust your generic type parameter T to be Color instead of Color?, so that you end up with:

final ItemBuilder<Color>? itemBuilder;

Pass callback with nullable parameter

Alternatively, you can adjust the callback you are passing accordingly:

itemBuilder: (Color? color) => Container(height: 100.0, color: color)
Related