flutterdartsingle-threaded

Flutter update progress in compute method


I have to save many images to the device to make videos.
As saving multiple images takes so much time and resources, I use compute to save images.

I want to show the progress in saving images so that users can notice how much time left for video.
But, calling progressDialog.update(progress: progress) in compute cause error like this

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function _handleBuildScheduled@587399801:.)

How can I show progress in compute method?


Solution

  • Thanks to pskink, I find out solution.
    First, create RecceivePort and pass receivePort.sendPort to compute method.

    ReceivePort receivePort;
    
    myComputeFunction(args) {
        Int someParameter = args[0]
        String otherParameter = args[1]
        SendPort port = args[2]
    
        //if you want to send some message
        port.send("your message here(passing double was ok)")
    }
    
    
    callingComputeFunction() {
        await compute(myComputeFunction, [1, "string", receivePort.sendPort]);
    }
    

    And before you call compute, don't forget to receivePort.listen().

    receivePort.listen((dynamic message) {
          //do whatever you want to do with message!
        });