如何在 Dart 中断言失败时打印消息?

How to print a message when an assert fails, in Dart?

我们想在 assert() 失败时打印一条消息。目前在 Dart 中,断言只需要一个布尔值。我们想为开发人员提供明确的原因和说明,说明在断言失败时该怎么做。

存在解决方法的未决问题https://github.com/dart-lang/sdk/issues/6190#issuecomment-119103626

assert(() => test || throw "message");

我试过了,但这种方法行不通。稍微修改的工作版本

var test = false;
assert(test ? true : throw "message");

另见

Dart 1.22 起,assert() 接受可选消息。

assert(configFile != null, "Tool config missing.");

如果断言失败,它会产生如下内容:

Unhandled exception:
'file:///.../main.dart': Failed assertion: line 9 pos 10:
'configFile != null': Tool config missing.
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:33)
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:29)
#2      main (file:///.../main.dart:9:10)

请注意,错误消息包括实际断言 (configFile != null)。

补充一下,如果您通过命令行执行 dart 文件,则需要按如下方式启用断言,请参阅参考资料 here:

dart --enable-asserts main.dart