LoginSignup
0

More than 3 years have passed since last update.

Flutter gallery_saver Androidのみ保存でエラーになる問題の解決

Last updated at Posted at 2020-03-23

gallery_saver は、写真・画像をカメラロール、ギャラリーに保存するライブラリ。
※ 使用バージョン gallery_saver 1.0.7

Androidのみ、同一ファイル名で保存をかけた場合、エラーとなる問題がある。

発生するエラー。

E/AndroidRuntime(21661): FATAL EXCEPTION: DefaultDispatcher-worker-1
E/AndroidRuntime(21661): Process: com.example.myapp, PID: 21661
E/AndroidRuntime(21661): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
E/AndroidRuntime(21661):    at android.content.ContentUris.parseId(ContentUris.java:85)
E/AndroidRuntime(21661):    at carnegietechnologies.gallery_saver.FileUtils.insertImage(FileUtils.kt:79)
E/AndroidRuntime(21661):    at carnegietechnologies.gallery_saver.GallerySaver$saveMediaFile$1$success$1.invokeSuspend(GallerySaver.kt:69)
E/AndroidRuntime(21661):    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
E/AndroidRuntime(21661):    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
E/AndroidRuntime(21661):    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
E/AndroidRuntime(21661):    at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
E/AndroidRuntime(21661):    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)
D/FlutterView(21661): Detaching from a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@97f0662

問題は確認されているがリリースまで進んでいない模様。
fix error if image was selected twice #41

関連issue

ひとまずの解決として、保存をかけたい一時保存しているファイルのファイル名を、ランダムにするなどして対応することで、エラーが発生せず保存ができた。

/// ランダムな文字列を生成するメソッド
static String randomString(int length) {
  const _randomChars =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const _charsLength = _randomChars.length;

  final rand = Random();
  final codeUnits = new List.generate(
    length,
    (index) {
      final n = rand.nextInt(_charsLength);
      return _randomChars.codeUnitAt(n);
    },
  );
  return new String.fromCharCodes(codeUnits);
}

// GallerySaver.saveImageに渡すため一時保存するファイル名をランダムにする
const tmpFileName = randomString(10) + '.png';

参考URL

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