0

We have:

final Widget? body;

And later in code:

final content = Column(
  children: [
    ...items,
    if (body != null) body!
  ],
);

Why I have to add ! sign, after body?

Without ! I receive:

The element type 'Widget?' can't be assigned to the list type 'Widget'.

In pubspec.yaml

environment:
  sdk: '>=2.12.0-0 <3.0.0'
Thomas Banderas
  • 1,681
  • 1
  • 21
  • 43

1 Answers1

0

The exclamation sign after variable or function means converting of nullable variable or function to non-nullable value. Because as you may know widget cannot be null.

const insets = EdgeInsets.all(10.0);
Widget? widget1 = insets;
Widget widget2 = insets;
assert(widget1! == widget2);

BambinoUA
  • 6,126
  • 5
  • 35
  • 51
  • 1
    It's obvious. Take a closer look, in the code, I ask if the body is null - `if (body != null) body!`. For me, this should be enough: `if (body != null) body`, because I have already asked if body is null – Thomas Banderas Feb 06 '21 at 14:12
  • No, not enough. Because variable is *nullable* (Widget?) but you need Widget. So it is similar to type casting. And the compiler also warn you. In c# also `int var = (int)Nullable(1);` – BambinoUA Feb 06 '21 at 14:19