简体   繁体   中英

Dart, Identifier with exclamation mark in the back

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?

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.

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;
  }
}

PS

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM