'How to save Base64 String to file and view it using Flutter

I need to download and view file (if possible, for Image, PDF, etc) using Flutter. My problem is, the file that I want to download is Base64 String. How can I achieve that using Flutter??



Solution 1:[1]

Following is the code snippet to decode base64 string and save it as a file on the local device. please note in terms of viewing files, image and pdf would require different libraries.

Future<String> _createFileFromString() async {
final encodedStr = "put base64 encoded string here";
Uint8List bytes = base64.decode(encodedStr);
String dir = (await getApplicationDocumentsDirectory()).path;
File file = File(
    "$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + ".pdf");
await file.writeAsBytes(bytes);
return file.path;
 }

Solution 2:[2]

Google Chrome does not let open tab with Url base64 encode, like "data:application/pdf;base64,JVBERi0xLjQKJeLj..." with javascript, so you can not open url with url_launcher, but you can download file.

Here is my code:

import 'dart:html' as html;
...
Future<void> downloadFile() {
  final urlString = "data:application/pdf;base64,JVBERi0xLjQKJeLj...";
  html.AnchorElement anchorElement = html.AnchorElement(href:urlString);
  anchorElement.download = urlString;
  anchorElement.click();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vilash Patel
Solution 2 mirxtrem apps