Update: Check down below about null-safety
additions.
What @jamesdlin said is enough. In addition, if you need real example, think about this:
import 'package:meta/meta.dart';
class Product {
final int id;
final String name;
final int price;
final String size;
final String image;
final int weight;
const Product({
@required this.id,
@required this.name,
@required this.price,
this.size,
this.image,
this.weight,
}) : assert(id != null && name != null && price != null);
}
We have products and they must have price, id and name. But we can handle other fields like, for example image for something generic or blank image icon etc. Also size and weight is not a must.
So, at the end we must ensure that required fields must not be null because they are mandatory. If you do this, you'll handle null values during development instead getting error on released application.
Don't forget this(from docs
):
In production code, assertions are ignored, and the arguments to assert aren’t evaluated.
Null-safety update:
Since this is topic about assert
, the fact that Dart is nullable
or not doesn't mean anything. Because assert
is all about making, well, assertions.
A simple example would be:
final text = Text('foo');
assert(text.data == 'foo', 'The data inside the Text must be foo!');
But in our specific example, we need to make some changes. Because id
, name
or price
cannot be null with that syntax. Let's make some differences:
import 'package:meta/meta.dart';
class Product {
final int id;
final String name;
final double price;
final String? size;
final String? image;
final int? weight;
const Product({
required this.id,
required this.name,
required this.price,
this.size,
this.image,
this.weight,
}) : assert(id > 0 && name.isNotEmpty && price > 0.0);
}
Because they are null-safe, we need to play around zero-values
.