Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart, Identifier with exclamation mark in the back

Tags:

flutter

dart

Recently I have been developing mobile aplication with flutter, when I looking at the source code for TickerProvider I see these lines:

mixin SingleTickerProviderStateMixin<T extends StatefulWidget> on State<T> implements TickerProvider {
Ticker? _ticker;

  @override
  Ticker createTicker(TickerCallback onTick) {
    ...
    _ticker = Ticker(onTick, debugLabel: kDebugMode ? 'created by $this' : null);
    return _ticker!;
  }

...
}

I'm interested with this line:

return _ticker!;

I have seen boolean identifier with exclamation mark in the front meaning that it will return the opposite value of it, but I never see this one. Can someone tell me what this does?

like image 269
landfire13224 Avatar asked Jan 16 '21 11:01

landfire13224


People also ask

What does the exclamation mark mean in Dart?

"!" is a new dart operator for conversion from a nullable to a non-nullable type. Read here and here about sound null safety. Use it only if you are absolutely sure that the value will never be null and do not confuse it with the conditional property access operator.

What does ~/ mean in Dart?

~ is currently only used for. ~/ Divide, returning an integer result. and ~/= integer division and assignment.

Why is there an exclamation point in flutter?

Non Nullable Type — Exclamation mark ( !) Appending ! to any variable tells the compiler that the variable is not null, and can be used safely.

What is null-aware operator in Dart?

Null-aware operators in dart allow you to make computations based on whether or not a value is null. It's shorthand for longer expressions. A null-aware operator is a nice tool for making nullable types usable in Dart instead of throwing an error.


2 Answers

It's part of the null safety that Dart have.

You can read about it here

If you’re sure that an expression with a nullable type isn’t null, you can add ! to make Dart treat it as non-nullable

Example:

int? aNullableInt = 2;
int value = aNullableInt!; // `aNullableInt!` is an int.
// This throws if aNullableInt is null.
like image 126
Dominik Šimoník Avatar answered Nov 11 '22 15:11

Dominik Šimoník


For betrer undestanding (by analogy with the action of the algorithm itself).
This operator acts as the following inline internal function (at least similarly):

T cast<T>(T? value) {
  if (value == null) {
    throw _CastError('Null check operator used on a null value');
  } else {
    return value;
  }
}

P.S.

Forgot to add.
Based on the error messages that are generated at runtime, we can conclude that this operator is called the Null check operator, which may mean that it checks the value for null and throws an exception if the value is null.

No magic!

like image 45
mezoni Avatar answered Nov 11 '22 14:11

mezoni