Reputation: 1500
In my Flutter app I have a section where users can download a list of images and save them to the device. For the download basicly I'm using the following code:
String imagePath = file["image"];
var appDocDir = await getTemporaryDirectory();
String savePath = appDocDir.path + "/$uniqueID.jpg";
await Dio().download(imagePath, savePath);
await ImageGallerySaver.saveFile(savePath);
The problem: This process freezes my UI.
I tried to write parts of it into a compute
to isolate the process. But on await getTemporaryDirectory()
and await Dio().download(imagePath, savePath);
the isolated function hangs. I think that we cannot use Third Party packages on isolated environment.
Do you have an idea what could I do to isolate this parts of code?
EDIT This is the entire loop:
await Future.forEach(files, (file) async {
entriesController.downloadIndex.value++;
if (file["video"] != null && file["video"].isNotEmpty) {
String videoPath = file["video"];
var appDocDir = await getTemporaryDirectory();
String savePath = appDocDir.path + "/$uniqueID.mp4";
await Dio().download(videoPath, savePath);
await ImageGallerySaver.saveFile(savePath);
}
if (file["video"] == null || file["video"].isEmpty) {
String imagePath = file["image"];
var appDocDir = await getTemporaryDirectory();
String savePath = appDocDir.path + "/$uniqueID.jpg";
try {
await Dio().download(
imagePath,
savePath,
);
} catch (e) {
print(e);
}
await ImageGallerySaver.saveFile(savePath);
}
});
Upvotes: 2
Views: 675
Reputation: 7601
try to use this package, flutter_isolate, it allows third party package in isolate:
import 'package:flutter_startup/flutter_startup.dart';
import 'package:flutter_isolate/flutter_isolate.dart';
void isolate2(String arg) {
FlutterStartup.startupReason.then((reason){
print("Isolate2 $reason");
});
Timer.periodic(Duration(seconds:1),(timer)=>print("Timer Running From Isolate 2"));
}
void isolate1(String arg) async {
final isolate = await FlutterIsolate.spawn(isolate2, "hello2");
FlutterStartup.startupReason.then((reason){
print("Isolate1 $reason");
});
Timer.periodic(Duration(seconds:1),(timer)=>print("Timer Running From Isolate 1"));
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final isolate = await FlutterIsolate.spawn(isolate1, "hello");
Timer(Duration(seconds:5), (){print("Pausing Isolate 1");isolate.pause();});
Timer(Duration(seconds:10),(){print("Resuming Isolate 1");isolate.resume();});
Timer(Duration(seconds:20),(){print("Killing Isolate 1");isolate.kill();});
runApp(MyApp());
}
Upvotes: 2