Table of contents
No headings in the article.
In modern mobile app development, it's common to encounter scenarios where you need to download files such as PDF documents. One approach is to encode the file as a Base64 string and then download it. In this article, we will explore how to download a Base64 string as a PDF file in a Flutter application.
Prerequisites: To follow along with this tutorial, make sure you have the following prerequisites:
Flutter SDK installed on your machine
A code editor (e.g., Visual Studio Code, Android Studio)
Basic knowledge of Flutter and Dart programming language
Created methods for a network request to fetch data from an API server
SO let's get started by setting up a Flutter project or using an existing one. Open your preferred code editor and create a new Flutter project by running the following command in the terminal:
flutter create pdf_download
dependencies:
flutter:
sdk: flutter
external_path: ^1.0.3
flutter_screenutil:
nb_utils:
Save the file and run flutter pub get
in the terminal to fetch the dependencies.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:nb_utils/nb_utils.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await initialize();
runApp(
const MyApp(),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
return ScreenUtilInit(
designSize: Size(logicalWidth(), logicalHeight()),
builder: (BuildContext context, Widget? child) => MaterialApp(
debugShowCheckedModeBanner: false,
navigatorKey: navigatorKey,
scrollBehavior: SBehavior(),
title: Strings.appName, // custom path to get application name
home: const DownloadPage(),
theme: ThemeData(
fontFamily: 'Inter', //predefined in pubspec.yaml
),
),
);
}
}
Create the file download function: Create a new Dart file, such as download_utils.dart
, and define a function to handle the pdf file download:
import 'dart:io';
import 'dart:convert';
import 'package:external_path/external_path.dart';
import 'package:nb_utils/nb_utils.dart';
//fileName is a combination of the file name and file type(.pdf) example: file.pdf
void downloadBase64String(String base64String, String fileName, BuildContext context) async {
List<int> bytes = base64.decode(base64String);
String path = await ExternalPath.getExternalStoragePublicDirectory(
ExternalPath.DIRECTORY_DOWNLOADS);
String filePath = path + '/$fileName';
debugPrint(filePath); // to display the file path on the terminal during debugging
File file = File(filePath);
await file.writeAsBytes(bytes);
snackBar(context,
title: 'File downloaded successfully',
backgroundColor: black,
textColor: white);
}
Implement the download functionality: In your Flutter application, create a new screen or widget where you want to trigger the download. In our case, we would name it DownloadPage
widget:
import 'package:flutter/material.dart';
import 'package:pdf_download/download_utils.dart';
class DownloadPage extends StatelessWidget {
final String base64String;
const DownloadButton({required this.base64String});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () async {
String fileString = base64String.replaceAll('data:application/pdf;base64,', '');
downloadBase64String(fileString, "unique-name.pdf");
//you can opt to write a function that will generate unique file name so it does not overwrite the previously downloaded file
},
child: Text('Download PDF'),
);
}
}
In this article, we learned how to download a Base64 string from a server as a PDF file in a Flutter application. There is a slight difference to what is found online ( await getExternalStorageDirectory();)
as there is direct access to the storage path on an Android after downloading using the external_path package. With this knowledge, you can enhance your Flutter applications by enabling users to download and interact with PDF documents seamlessly. I will like to know about your implementation in the comment section. cheers...