How can I fix my gif saving function in flutter ? Right now it saves only 1 frame . Future _saveTestAnimation() async { // 1. Show loading state _isSavingAnimation.value = true; _saveProgress.value = 0.0; // NOTE: This test skips the permission check for simplicity, assuming it's already granted.
try {
// 2. Define animation parameters
const int width = 200;
const int height = 200;
const double durationSeconds = 2.0;
const int fps = 15;
final totalFrames = (durationSeconds * fps).toInt();
var size = Size(width.toDouble(), height.toDouble());
final gifEncoder = img.GifEncoder(
delay: 1000 ~/ fps, // delay in milliseconds
);
// 3. Loop, render a SIMPLE frame, and add to GIF
for (int i = 0; i < totalFrames; i++) {
final progress = i / (totalFrames - 1); // 0.0 to 1.0
code
final recorder = ui.PictureRecorder();
final canvas = Canvas(
recorder,
Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()),
);
// --- Start of a simple, guaranteed-to-be-different frame ---
// Draw a black background (CRITICAL to avoid ghosting)
canvas.drawColor(Colors.black, BlendMode.src);
// Create a red square
final paint = Paint()..color = Colors.red;
// Move the square from left to right based on progress
final rect = Rect.fromLTWH(
progress * (width - 50),
height / 2 - 25,
50,
50,
);
canvas.drawRect(rect, paint);
// --- End of simple frame ---
// Convert canvas to image bytes
final picture = recorder.endRecording();
final renderedImage = await picture.toImage(width, height);
final byteData = await renderedImage.toByteData(
format: ui.ImageByteFormat.rawRgba,
);
if (byteData == null) continue;
final imageForGif = img.Image.fromBytes(
width: renderedImage.width,
height: renderedImage.height,
bytes: byteData.buffer,
order: img.ChannelOrder.rgba,
);
gifEncoder.addFrame(imageForGif);
// Update progress UI
_saveProgress.value = progress;
await Future.delayed(Duration.zero);
}
// 4. Finalize GIF and save to gallery
final gifBytes = gifEncoder.finish();
if (gifBytes == null) {
throw Exception("Failed to encode TEST GIF.");
}
final tempDir = await getTemporaryDirectory();
final filePath =
'{tempDir.path}/test_animation_{DateTime.now().millisecondsSinceEpoch}.gif';
final file = File(filePath);
await file.writeAsBytes(gifBytes);
final result = await ImageGallerySaver.saveFile(filePath);
if (!mounted) return;
if (result['isSuccess'] == true) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('TEST Animation saved to gallery!')),
);
} else {
throw Exception(
result['errorMessage'] ?? 'Failed to save TEST animation',
);
}
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error saving TEST animation: $e')),
);
} finally {
// 5. Reset UI state
_isSavingAnimation.value = false;
_saveProgress.value = 0.0;
}
}
Assistant
Your code is almost correct for generating a multi-frame GIF in Flutter, but the issue is likely with the way you are using the image package's GifEncoder. The most common cause for only one frame being saved is:
Not using the same GifEncoder instance for all frames (but you are).
Not using the correct byte format (should be rawRgba with ChannelOrder.rgba).
Not calling finish() at the right time (you are).
A bug in the image package (possible, but rare for this use case).
Let's check a few things and try a fix:
1. Check the image package version
Make sure you are using the latest version of the image package. Old versions had bugs with GIF encoding.
yaml
dependencies:
image: ^4.1.7 # or latest
2. Check the addFrame usage
You are using:
dart
gifEncoder.addFrame(imageForGif);
This is correct. But sometimes, the encoder needs the duration parameter per frame.
Try this: