LoginSignup
1
0

List型のfirstやlastを使う際は要注意

Posted at

安直にfirstやlastを使って要素にアクセスしてしまっており、不具合を起こしてしまっていたので備忘録。

例えば以下のコードはエラーになります。

  final List<String> list = [];
  print(list.last);  // Uncaught Error: Bad state: No element

そのため以下のように修正する必要があります。

  final List<String> list = [];
  print(list.isEmpty ? '' : list.last);

first、lastでの要素アクセスについてでしたが、単純にインデックスを使ったアクセスでも要素が空だとエラーになるので注意が必要です。

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