//////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // current code //////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////

@override Widget build(BuildContext context) { return Column( children: [ Button( onPressed: () => myFunction(); ) ] ); }

//////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // new code //////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////

Future<ReceivePort> makeIsolate() async { ReceivePort receivePort = ReceivePort(); Isolate isolate = await Isolate.spawn( isolateFunction, receivePort.sendPort, ); return receivePort; }

void isolateFunction(SendPort sendPort) async { //Do long running task for (int i = 0; i < 100000; i++) { doSth();

double progress = i/100000; // Calculating progress based on loop index
sendPort.send(progress);

} sendPort.send(true); // Send true on completion to indicate work is done }

Stream<double> progress() async* { ReceivePort receivePort = await makeIsolate(); await for(var event in receivePort) { if(event is double) { yield event; } if(event is bool) { receivePort.close(); return; } } }

@override Widget build(BuildContext context) { return Column( children: [ Button( onPressed: () => myFunction(); ), StreamBuilder( stream: progress(), builder: (context, snapshot) { if(snapshot.connectionState == ConnectionState.done) { //show successful completion here } if(snapshot.hasData) { return CircularProgressIndicator( value: snapshot.data, ); } return CircularProgressIndicator(); } ) ] ); }