BoxPainter createBoxPainter([onChanged]) => The parameter onChanged can't have a value of null


I’ve copied/pasted some sample code for creating a custom BoxDecoration:

class FrameDecoration extends Decoration {
  BoxPainter createBoxPainter([onChanged]) {
    return _CustomDecorationPainter();

I get this error:

The parameter ‘onChanged’ can’t have a value of ‘null’ because of its
type, but the implicit default value is ‘null’.

Try adding either an explicit non-null default value or the ‘required’

OK, that makes sense: it’s a null safety issue. My pubspec.yaml "environment": sdk: ">=2.12.0 <3.0.0"

So I try adding "required":

class FrameDecoration extends Decoration {
  BoxPainter createBoxPainter(required [onChanged]) {
    return _CustomDecorationPainter();

This time the error is:

‘FrameDecoration.createBoxPainter’ (‘BoxPainter Function(void
Function())’] isn’t a valid override of ‘Decoration.createBoxPainter’
(‘BoxPainter Function(‘void Function()])’).

I tried several other things – no joy.

Both messages also say:

The onChanged argument … can be omitted if there is no change that
the painter will change.

I tried "no parameters" ("createBoxPainter()"), and I tried an empty list ("createBoxPainter([])"). Still no joy.

All I want is to create my own "Decoration" class, with a custom "paint()" method.

Q: What’s the correct syntax for omitting onChanged from createBoxPainter()?

Q: What’s the recommended syntax for "createBoxPainter()" in this example?

pedro pimont gave me the syntax I was lookingfor:

 BoxPainter createBoxPainter([VoidCallback? onChanged]) {
   return _CustomDecorationPainter();
 // <= Explicitly adding the type, and making it nullable, resolved the compile error


The createBoxPainter from the Decoration class you’re trying to override takes an optional VoidCallback onChanged parameter so if you don’t provide it with a default value, you must also mark it as nullable using ?, try this:

BoxPainter createBoxPainter([VoidCallback? onChanged])

Also, although none of these below will work, regarding the Dart syntax, you’re marking an optional parameter as required, this is not allowed.

Either use a named parameter to use the required keyword using {}:

BoxPainter createBoxPainter({required Function onChanged})

Or make it required by removing []

BoxPainter createBoxPainter(Function onChanged)

Answered By – pedro pimont

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *