Flutter image_gallery_Saver plug-in cause UI thread gets stuck when saving pictures, and getting error when I try create it by compute

Viewed 33
      try {
        //CheckPermission
        if (await Permission.storage
            .request()
            .isGranted) {

          final result = await SaveImageToKoi(post.fimgUrl!.url!);

          print(result);

          if (result != null)
            BotToast.showText(text: "Success");
          else
            BotToast.showText(text: "Error");
        }
      } catch (e) {}
    },

dynamic SaveImageToKoi (koi_url) async {
  print(koi_url);
  var response = await Dio().get(
      koi_url,
      options: Options(responseType: ResponseType.bytes));

  final result = await ImageGallerySaver.saveImage(
      Uint8List.fromList(response.data),
      quality: 100);
    }

I am trying to use the below library: https://pub.dev/packages/image_gallery_saver

And when I am saving picture, it will cause the UI thread to get stuck. The stuck time depends on the size of the image An error will be reported when trying to create a new thread by using compute to save. I don't know how to solve it, I just started learning Flutter and hope to receive

I guess the plug-in was written by Kotlin, and there was a problem when the interface communication was created by Dart

Thanks.

This is an error when I use compute

In platform_channal.dart

Thrown by

BinaryMessenger get binaryMessenger => _binaryMessenger ??

ServicesBinding.instance!.defaultBinaryMessenger;

exception = {_CastError} Null check operator used on a null value

Errors when using Compute

1 Answers

From your question it is not clear where your try/catch block code executes, but from what you describe I assume it is in a UI method such as build. If that is the case then indeed this code will block the UI, because while your statement final result = await SaveImageToKoi will yield to allow other methods to run, it won't proceed past this statement until the save is done.

You should perform the save function elsewhere (not blocking UI), and upon completion of the save trigger the UI to rebuild (typically by calling setState() in a Stateful Widget. For example, if you had a button in your UI that you want to trigger the save, then in your build function you might have this widget:

RaisedButton(
  onPressed: () => {
    SaveImageToKoi(post.fimgUrl!.url!).then((result) {
      print(result);
      setState(() {}); // this will trigger the UI redraw
   });
  },
  child: new Text('Click me'),
),

The SaveImageToKoi statement here will not block, and upon completion of the save the code in the then argument is executed, with the result of the save operation. It is there that you call setState to trigger the UI refresh (if necessary - for example if you wanted to show the result in some way)

Related