Freezed: Add assert(field != null) functionality

Created on 11 Feb 2020  路  8Comments  路  Source: rrousselGit/freezed

Hi there,
first of all: Great package!

The only thing I am missing at this point is the possibility to ensure fields to be non null.
Normally I would use assert(field != null) in the constructor to make a field non-nullable.
It would be really useful to have this feature on freezed classes to make nullability errors easier to prevent.

Thanks!

enhancement

Most helpful comment

If we're going with custom annotations, I would go with a @nullable annotation instead:

@freezed
abstract class MyClass with _$MyClass {
  factory MyClass({
    @required String notNullable,
    @required @nullable String nullable,
  }) = _MyClass;
}

Thought?

All 8 comments

I didn't add it because I can't think of any good enough syntax for it.
@required cannot be used here, because we can have required nullable parameters.

Unless you have a proposal (that doesn't rely on a custom annotation), then I'd prefer to wait for non-nullable types to land.
Non-nullable types should remove the need for such an assertion.

Would it be possible to check if the package "non_null" is installed and if so use its @nonNull annotation?

I'd love to have this. This way I could replace all my "data classes" with freezed classes.
I'd add a @nonNull annotation to this project.

Now that freezed will have an annotation package, it should be fine.

If we're going with custom annotations, I would go with a @nullable annotation instead:

@freezed
abstract class MyClass with _$MyClass {
  factory MyClass({
    @required String notNullable,
    @required @nullable String nullable,
  }) = _MyClass;
}

Thought?

I like it! Will only @required properties be checked for null or all properties which are not annoted with @nullable?

All properties unless:

  • they are annoted with @nullable
  • they are named parameters without a @required
  • they are positional optional parameter

This will also be applied to copyWith and the future copyAs by the way.

Was this page helpful?
0 / 5 - 0 ratings