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
The issue with your GIF saving function is that the img.Image.fromBytes method is not being provided the correct data type. Specifically, you're passing a ByteBuffer instead of a List<int> (or Uint8List), which is required by the image package. This leads to the encoder failing to process subsequent frames correctly, resulting in only the first frame being saved.
✅ Fix: Convert ByteBuffer to Uint8List
Update the line where imageForGif is created as follows:
dart
final imageForGif = img.Image.fromBytes(
width: renderedImage.width,
height: renderedImage.height,
bytes: byteData.buffer.asUint8List(), // ✅ Correct: Convert ByteBuffer to Uint8List
order: img.ChannelOrder.rgba,
);
🔍 Why This Matters
The img.Image.fromBytes method expects a List<int> (or Uint8List) for the bytes parameter. The byteData.buffer is a ByteBuffer, which is not compatible. Using asUint8List() converts the buffer into a list of bytes that the image package can process correctly.
🧪 Additional Checks
Ensure image package is up to date:
yaml
dependencies:
image: ^3.0.1
Verify that renderedImage is not null:
dart
final renderedImage = await picture.toImage(width, height);
if (renderedImage == null) continue;
Check if the GIF encoder is functioning correctly:
If the issue persists after fixing the bytes parameter, consider testing with a simple static image to ensure the encoder works as expected.
🧾 Final Code Snippet (Key Fix)
Here’s the corrected section of your code:
dart
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.asUint8List(), // ✅ Fixed here
order: img.ChannelOrder.rgba,
);
gifEncoder.addFrame(imageForGif);
📝 Summary
Problem: You were passing a ByteBuffer instead of a Uint8List to img.Image.fromBytes.
Solution: Convert the ByteBuffer to a Uint8List using asUint8List().
Result: All frames should now be added to the GIF, and the final output will contain the full animation.
Once this fix is applied, your GIF should save all frames correctly.