LoginSignup
4
1

More than 3 years have passed since last update.

DartでOptionalの変数をアンラップして利用する

Posted at

目的

Optionalな変数をアンラップして利用したい。

環境

  • Flutter 2.0.1
  • Dart 2.12.0

コード

ifnull 判定を行い、reutrn で関数スコープ抜けると、
その後のコードでは、 unwrap されたとみなされます。

  void func(int? value) {

    if (value == null) {
      return;
    }

    print(value + 10);
  }

swift の guard文の逆みたいな感じですね。

ただ、Android Studio では if を入れる事で確かにコンパイルが通るようにはなるのですが、
swift の用に明示的に Optional でない int に再代入されるわけではなく、
若干、ルール縛りみたいな印象を受けるので、
個人的には swift の guard文 の方が明瞭で好きです。

参考にしたサイト

Swift Optional vs Dart sound null safety _ I should go to sleep
https://ishouldgotosleep.com/computer-science/swift-optional-vs-dart-sound-null-safety/

4
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1