From 31e3ae89dbd4095022503bb75484b7e179c73312 Mon Sep 17 00:00:00 2001 From: fzyzcjy <5236035+fzyzcjy@users.noreply.github.com> Date: Wed, 7 Jun 2023 08:29:20 +0800 Subject: [PATCH] Show error message in release mode when box is not laid out without losing performance (#126302) Close https://github.com/flutter/flutter/issues/126303 When I encounter bugs in production environment saying null pointer error on `return _size!`, I wish I could know more information! However, currently the information is revealed by `assert(hasSize, 'RenderBox was not laid out: $this');`, thus *only* in debug mode can I know what is `this` (and/or more information that can be added), while in release mode I can only see a stack trace saying it is `RenderBox.size` that throws - nothing more :/ Therefore, it is intuitive to add this extra information in release mode. However, will it affect performance? We all know this is in critical path and should be quite careful. Thus I did some experiments: https://godbolt.org/z/zPPPf5969 From my naive understanding of assembly, the two versions of code (`size!` vs `size ?? throw`) has the same assembly, except that they throw different types of errors. In other words, when there is no error, both code should be equivalent; when there is an error, surely the new code will be slower since it calls `this.toString()`, but the error handling process is rare and already heavy, so this is not a problem. ![image](https://user-images.githubusercontent.com/5236035/236962182-b9450d59-a2ac-426f-8300-3c7edcadf35e.png) --- packages/flutter/lib/src/rendering/box.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/flutter/lib/src/rendering/box.dart b/packages/flutter/lib/src/rendering/box.dart index c1c06cb8d5..9b9a7c4313 100644 --- a/packages/flutter/lib/src/rendering/box.dart +++ b/packages/flutter/lib/src/rendering/box.dart @@ -1985,7 +1985,7 @@ abstract class RenderBox extends RenderObject { } return true; }()); - return _size!; + return _size ?? (throw StateError('RenderBox was not laid out: $runtimeType#${shortHash(this)}')); } Size? _size; /// Setting the size, in debug mode, triggers some analysis of the render box,