5
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.

「Bad state: No element」というエラーの対処法

Posted at

はじめに

プチ記事というか、私的なメモ、備忘録に近い内容ですが、同じくエラーに困っている方がいればとおもい公開しておきます。
Flutterで開発中に、「Bad state: No element」というエラーが出たのですが、スタックトレースを遡っても原因がよくわからなかったので、手当たり次第にググって解決法を見つけました。
同じく原因わからない方の参考になれば幸いです。

解決法

解決法というかエラーの原因ですが、ListfirstWhereを使っている箇所でリストが空の場合や一致する要素がない場合に発生するようです。
参考記事

なので、私の場合、怪しい個所を探して、リストが空の場合にガードする処理を入れて防ぎました。

参考記事によると、orElseを指定すると大丈夫みたいです。
list.firstWhere((a) => a == b, orElse: () => print('No matching element.'));

また、下記のような拡張メソッドもあるみたいです。

import 'package:collection/collection.dart';

list.firstWhereOrNull((element) => element == other);
5
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
5
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?