1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Flutter】" ! "を使わずにThe property can't be unconditionally accessed because the receiver can be 'null'.を解決して安全性を高める

Posted at

はじめに

The property can't be unconditionally accessed because the receiver can be 'null'
というエラーが出ると、私はいつも!をつけていましたが、これでは少し安全性が不安なので、nullチェックを入れた方がいいと知りました。

エラーの出るコード

void setUserId(int index, String? value) {
    if (value == null) return;
    final userIds =
        List<String>.from(state.appConfig.userIds);

!で対処した場合

void setUserId(int index, String? value) {
    if (value == null) return;
    final userIds =
        List<String>.from(state.appConfig!.userIds);// !でnullでないことを強制させる

nullチェックを用いる場合

void setUserId(int index, String? value) {
    if (value == null) return;
    final appConfig = state.appConfig; // 変数として確保する
    if (appConfig == null) return; // nullならリターンさせる

    final userIds = List<String>.from(appConfig.userIds);// エラーは起きない
  }
1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?