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

[Flutter]空文字列でFileオブジェクトを作成するとリードエラーをキャッチできない

0
Last updated at Posted at 2025-08-23

ファイルを読むのに次のようなコードを書いてpathに""(空文字列)を渡したら、readAsString()で例外を起こしたがキャッチされずにアプリが落ちた。

  Future<void> readFile(String path) async {
    try {
      final file = File(path);
      final content = await file.readAsString();
      ...
    } catch (e, stackTrace) {
      print("Error reading file: $e");

Copilotにどーゆーこっちゃと聞いたら、path が空文字列("")だと File("") となり、
カレントディレクトリを指してしまう。ディレクトリに対して readAsString() を呼ぶと、FileSystemException ではなく別の例外(IsADirectoryError など)が発生し、catchできない場合があるのだそーな。

File()にフルパスでない文字列を渡すとカレントディレクトリからの相対指定となる。空文字だとカレントディレクトリそのものを指すという理屈であろう。こっちはまあ納得できるが、ディレクトリに対してreadAsString()を呼ぶとcatchできないというのは困る。さらにCopilotにいろいろ聞いてみたが、Copilotがこーやったらcatchできると出してきた案はことごとく失敗した。

しかたがないので今のところ対策は実行前に空文字かどうか判定するということになる。これでもpathが存在するディレクトリだったら落ちてしまうかもしれないが、存在しないファイルを指定すると例外をcatchすることができた。

  Future<void> readFile(String path) async {
    if (path.isEmpty) {
      return;
    }
    try {
      final file = File(path);
      final content = await file.readAsString();
      ...
0
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
0
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?