Extreme Lag After Loading Palette from Image
135
I recommend using the flutter_isolate package to implement Isolates. The function you are using is a heavy function. Using an Isolated avoids putting too much pressure on the main thread.
Example code:
void updatePalette() async {
var cache = DefaultCacheManager();
File file = await cache.getSingleFile(url);
var port = ReceivePort();
var isolate = await FlutterIsolate.spawn(
computePalette,
[file.readAsBytesSync(), port.sendPort],
);
port.listen((msg) {
List<int> data = msg;
data.forEach((d) => colorList.add(Color(d));
isolate.kill();
port.close();
});
}
void computePalette(List<Object> args) async {
var image = args[0] as Uint8List;
var port = args[1] as SendPort;
var img = Image.memory(image);
var palette = await PaletteGenerator.fromImageProvider(
img.image,
maximumColorCount: 7,
);
List<int> colors = [];
palette.colors.forEach((element) => colors.add(element.value));
port.send(colors);
}
Author by
Billu Barber
Updated on December 31, 2022Comments
-
Billu Barber over 1 year
I am currently making a wallpaper app in Flutter. I am using the palette_generator package to extract colors from the image. The problem is while the app is extracting colors from the image. The UI freezes for a solid 3 seconds, after which the colors are shown on the screen. After the colors have been rendered, the whole screen suffers from jank and lag. All animations on that screen perform very badly. Popping off that screen removes the jank and lag. Here is the code I am using:
Future<PaletteGenerator?> updatePalette() async { var cache = DefaultCacheManager(); File file = await cache.getSingleFile(widget.wall.url); ui.Image image = await load(file); palette = await PaletteGenerator.fromImage( image, maximumColorCount: 7, ); return palette; } Future<ui.Image> load(File file) async { var data = await file.readAsBytes(); ui.Codec codec = await ui.instantiateImageCodec(data); ui.FrameInfo fi = await codec.getNextFrame(); return fi.image; } FutureBuilder<PaletteGenerator?>( future: updatePalette(), builder: (context, snapshot) { if (snapshot.hasData) return MyBottomSheet( wall: widget.wall, palette: snapshot.data); return LinearProgressIndicator(); }),
Is there anything I can do to fix this issue?