Is there any NotNull annotation in dart?

Issue

I have this little class:

class WidgetToImage extends StatefulWidget {
  final Function(GlobalKey key)  builder;

  const WidgetToImage({Key? key, @required this.builder}) : super(key: key);

  @override
  _WidgetToImageState createState() => _WidgetToImageState();
}

This chunk of code won’t compile because anybody can pass a null value for the builder parameter when constructing the WidgetToImage widget. I know I could make the builder nullable but this is not what I want because later I must be checking if it is null, etc. and semantically it doesnt make any sense. A valid builder must be always passed.

Is there any way to annotate this in dart to avoid converting builder property to a nullable type?

Solution

If you use Dart version 2.12, you get null safety as a language feature.
It seems you are already using that since your code contains Key?, which is the null-safety way of writing "nullable".
On the other hand, your this.builder parameter should have been marked as required (a keyword in null safe code) instead of the older @required annotation, so it doesn’t look like valid null safe code.

The code should read:

class WidgetToImage extends StatefulWidget {
  final Function(GlobalKey key)  builder;

  const WidgetToImage({Key? key, required this.builder}) : super(key: key);

  @override
  _WidgetToImageState createState() => _WidgetToImageState();
}

and then it’s a compile-time error for null-safe code to pass null as an argument to builder.
(Older non-null-safe code can still get away with passing null, but they’re asking for trouble then.)

You can add an assertion:

  const WidgetToImage({Key? key, required this.builder}) 
      : assert(builder as dynamic != null), 
        super(key: key);

that will tell people developing against your library to not pass in null from non-null-sound code, but only while developing with assertions enabled.

Answered By – lrn

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.