Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

flutter - What assert do in dart?

I just want to know what's the use of assert in a Dart. I was tried to figure it out by myself but I'm not able to do that. It would great if someone explains me about assert.

question from:https://stackoverflow.com/questions/56537718/what-assert-do-in-dart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...