PDF File is not downloading when using Dio in Flutter - android

I created a Pdf viewer screen and I added a button which should download the PDF from the URL when it's pressed. I display the pdf from an URL, it is displayed correctly but the download function is not working. I tried different examples and implementations found on the internet but nothing worked.
Let me know if you have any solution for this. Thanks
This is my dart class:
class _PdfViewerScreenState extends State<PdfViewerScreen> {
late PdfViewerController _pdfViewerController;
String uri = 'https://file-examples.com/wp-content/uploads/2017/10/file-example_PDF_1MB.pdf';
String filename = 'test.pdf'; // file name that you desire to keep
// downloading logic is handled by this method
Future<void> downloadFile(uri, fileName) async {
String savePath = await getFilePath(fileName);
Dio dio = Dio();
dio.download(
uri,
savePath,
);
}
Future<String> getFilePath(uniqueFileName) async {
String path = '';
Directory dir = await getApplicationDocumentsDirectory();
path = '${dir.path}/$uniqueFileName.pdf';
return path;
}
#override
void initState() {
_pdfViewerController = PdfViewerController();
super.initState();
}
#override
Widget build(BuildContext context) {
var theme = HolidayApp.of(context).theme;
return Scaffold(
appBar: AppBar(
title: Text(
Constants.downloadRequest,
style: theme.textTheme.heading3.copyWith(
fontWeight: FontWeight.w400,
),
),
actions: [_downloadButton(downloadFile(uri, filename))]),
body: SafeArea(
child: SfPdfViewer.network(
widget.pdfUrl,
controller: _pdfViewerController,
),
),
);
}
}
IconButton _downloadButton(Future f) {
return IconButton(
icon: const Icon(
Icons.download,
),
onPressed: () {
f;
},
);
}

Related

Flutter `Screenshot` package: Why isn't the `captureAndSave()` method saving an image to my (Android) device?

Preface:
I'm using the Screenshot package. In this package, there is a method captureAndSave() which saves a widget as an image to a specific location, however, when I call this function, my image is not being saved. Why?
Complete Code Example:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:screenshot/screenshot.dart';
class QrCodeScreen extends StatefulWidget {
const QrCodeScreen({Key? key}) : super(key: key);
#override
State<QrCodeScreen> createState() => _QrCodeScreenState();
}
class _QrCodeScreenState extends State<QrCodeScreen> {
final _screenshotController = ScreenshotController();
Image? image;
var doesTheImageExist = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (image == null)
TextButton(
child: Text("Save QR Code"),
onPressed: () async {
await _captureAndSaveQRCode();
image = await _loadImage();
setState(() {});
},
)
else
image!,
Text("Is the QR Code saved to your device? ${doesTheImageExist}"),
if (image == null)
Screenshot(
controller: _screenshotController,
child: _buildQRImage('_authProvider.user!.uid')),
],
),
);
}
Widget _buildQRImage(String data) {
return QrImage(
data: data,
size: 250.0,
gapless: false,
foregroundColor: Colors.black,
backgroundColor: Colors.white,
);
}
Future<String> get imagePath async {
final directory = (await getApplicationDocumentsDirectory()).path;
return '$directory/qr.png';
}
Future<Image> _loadImage() async {
return imagePath.then((imagePath) => Image.asset(imagePath));
}
Future<void> _captureAndSaveQRCode() async {
final path = await imagePath;
await _screenshotController.captureAndSave(path);
// It always returns false, although I'm saving the file using `captureAndSave` .
doesTheImageExist = File(path).existsSync();
}
}
The Question:
In the code above, when I click on the TextButton() that says "Save QR Code" it then calls _captureAndSaveQRCode() and _loadImage(). Hence my image should successfully be saved to my (Android) phone. However, I get an error:
Unable to load asset: /data/user/0/com.example.qr/app_flutter/qr.png
Full Traceback:
======== Exception caught by image resource service ================================================
The following assertion was thrown resolving an image codec:
Unable to load asset: /data/user/0/com.example.qr/app_flutter/qr.png
When the exception was thrown, this was the stack:
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:237:7)
<asynchronous suspension>
#1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:675:14)
<asynchronous suspension>
Image provider: AssetImage(bundle: null, name: "/data/user/0/com.example.qr/app_flutter/qr.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#5986d(), name: "/data/user/0/com.example.qr/app_flutter/qr.png", scale: 1.0)
====================================================================================================
Why isn't my image being saved to the device when calling _captureAndSaveQRCode()?
Side note:
I recently posted an answer (currently in Bounty) with (almost) the same code as in this question which does work correctly, so, what's the difference?
The problem was that I had an empty setState:
onPressed: () async {
await _captureAndSaveQRCode();
image = await _loadImage();
setState(() {});
},
)
So to solve the problem, I removed the setState and also got rid of the _loadImage() function.
And then updated the image variable within the TextButton():
TextButton(
child: Text("Save QR Code"),
onPressed: () async {
await _captureAndSaveQRCode();
setState(() {
doesTheImageExist = true;
image = image;
});
},
)
Complete working example:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:screenshot/screenshot.dart';
class QrCodeScreen extends StatefulWidget {
const QrCodeScreen({Key? key}) : super(key: key);
#override
State<QrCodeScreen> createState() => _QrCodeScreenState();
}
class _QrCodeScreenState extends State<QrCodeScreen> {
final _screenshotController = ScreenshotController();
Image? image;
var doesTheImageExist = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (image == null)
TextButton(
child: Text("Save QR Code"),
onPressed: () async {
await _captureAndSaveQRCode();
setState(() {
doesTheImageExist = true;
image = image;
});
},
)
else
image!,
Row(children: [
Text('hi'),
Text("Is the QR Code saved to your device? ${doesTheImageExist}")
]),
if (image == null)
Screenshot(
controller: _screenshotController,
child: _buildQRImage('_authProvider.user!.uid')),
],
),
);
}
Widget _buildQRImage(String data) {
return QrImage(
data: data,
size: 250.0,
gapless: false,
foregroundColor: Colors.black,
backgroundColor: Colors.white,
);
}
Future<String> get imagePath async {
final directory = (await getApplicationDocumentsDirectory()).path;
return '$directory/qr.png';
}
// Future<Image> _loadImage() async {
// return imagePath.then((imagePath) => Image.asset(imagePath));
// }
Future<void> _captureAndSaveQRCode() async {
final path = await imagePath;
await _screenshotController.captureAndSave(path);
// It always returns false, although I'm saving the file using `captureAndSave` .
doesTheImageExist = File(path).existsSync();
}
}
load image with Image.file(File(imagePath))
Image.Asset is for loading images defined in pubspec.yaml
Edit:
the path in captureAndSave is directory path. it takes another optional argument fileName.
// previous code
// i create new getter for directory
Future<String> get dirPath async {
final directory = (await getApplicationDocumentsDirectory()).path;
return directory;
}
Future<String> get imagePath async {
final directory = await dirPath;
return '$directory/qr.png';
}
Future<Image> _loadImage() async {
return imagePath.then((imagePath) => Image.file(File(imagePath)));
}
Future<void> _captureAndSaveQRCode() async {
final path = await dirPath;
await _screenshotController.captureAndSave(path, fileName: "qr.png");
// It always returns false, although I'm saving the file using `captureAndSave` .
doesTheImageExist = File(path).existsSync();
}
// the rest of the code

I want to get the video size from internet path for my flutter app

I'm trying to get the video file size and use it as a percent inside LinearPercentIndicator.
based on my search I found a code but for android how can I do like that on flutter.
final URL uri=new URL("http://your_url.com/file.mp4");
URLConnection connection;
try
{
connection=uri.openConnection();
connection.connect();
final String contentLengthStr=ucon.getHeaderField("content-length");
// do whatever
}
catch(final IOException exception)
{
}
PS: I'm using FFmpeg for downloading.
For instance, using dio plugin
dio using large size file downloader
url link : https://pub.dev/packages/dio
for Example
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
class LargeFileMain extends StatefulWidget {
#override
State<StatefulWidget> createState() => _LargeFileMain();
}
class _LargeFileMain extends State<LargeFileMain> {
final imgUrl =
'http://your_url.com/file.mp4';
bool downloading = false;
var progressString = "";
var file;
Future<void> downloadFile() async {
Dio dio = Dio();
try {
var dir = await getApplicationDocumentsDirectory();
await dio.download(imgUrl, '${dir.path}/myimage.jpg',
onReceiveProgress: (rec, total) {
print('Rec: $rec , Total: $total');
file = '${dir.path}/myimage.jpg';
setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + '%';
});
});
} catch (e) {
print(e);
}
setState(() {
downloading = false;
progressString = 'Completed';
});
print('Download completed');
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Large File Example'),
),
body: Center(
child: downloading
? Container(
height: 120.0,
width: 200.0,
child: Card(
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
SizedBox(
height: 20.0,
),
Text(
'Downloading File: $progressString',
style: TextStyle(
color: Colors.white,
),
)
],
),
),
)
: FutureBuilder(
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
print('none');
return Text('No Data');
case ConnectionState.waiting:
print('waiting');
return CircularProgressIndicator();
case ConnectionState.active:
print('active');
return CircularProgressIndicator();
case ConnectionState.done:
print('done');
if (snapshot.hasData) {
return snapshot.data;
}
}
return Text('No Data');
},
future: downloadWidget(file),
)),
floatingActionButton: FloatingActionButton(
onPressed: () {
downloadFile();
},
child: Icon(Icons.file_download),
),
);
}
Future<Widget> downloadWidget(String filePath) async {
File file = File(filePath);
bool exist = await file.exists();
if (exist) {
return Center(
// your video file using widget
);
} else {
return Text('No Data');
}
}
}

Download pdf from url, save to phones local storage in android in flutter

I'm working on a project, that requires me to download a pdf file from URL, once a button is tapped, and store it to phone storage (probably downloads folder).
Any ideas on how to do this? The file that is being downloaded is also not always the same and can be anything from an pdf to image.
You can use the Dio package to download files to your local storage using Dio().download
response = await dio.download("https://www.google.com/", "./xx.html");
Also you can check out this open source project as reference
I hope this would help you. Check if file is already present, if not then use the URL to fetch the file and save it in application directory.
Future<File> createFile() async {
try {
/// setting filename
final filename = widget.docPath;
/// getting application doc directory's path in dir variable
String dir = (await getApplicationDocumentsDirectory()).path;
/// if `filename` File exists in local system then return that file.
/// This is the fastest among all.
if (await File('$dir/$filename').exists()) return File('$dir/$filename');
///if file not present in local system then fetch it from server
String url = widget.documentUrl;
/// requesting http to get url
var request = await HttpClient().getUrl(Uri.parse(url));
/// closing request and getting response
var response = await request.close();
/// getting response data in bytes
var bytes = await consolidateHttpClientResponseBytes(response);
/// generating a local system file with name as 'filename' and path as '$dir/$filename'
File file = new File('$dir/$filename');
/// writing bytes data of response in the file.
await file.writeAsBytes(bytes);
/// returning file.
return file;
}
/// on catching Exception return null
catch (err) {
errorMessage = "Error";
print(errorMessage);
print(err);
return null;
}
}
The below code works on both iOS and Android. Replace ".pdf" with ".jpg" if you are looking for downloading an image.
In pubspec.yaml, paste the below code under dependencies
dio: any
path_provider: any
file_utils: any
permission_handler: any
In android/app/src/main/AndroidManifest.xml paste the below lines outside the <application> tags
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Below is the code :
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:async';
import 'package:file_utils/file_utils.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:intl/intl.dart';
void main() => runApp(Downloader());
class Downloader extends StatelessWidget {
#override
Widget build(BuildContext context) => MaterialApp(
title: "File Downloader",
debugShowCheckedModeBanner: false,
home: FileDownloader(),
theme: ThemeData(primarySwatch: Colors.blue),
);
}
class FileDownloader extends StatefulWidget {
#override
_FileDownloaderState createState() => _FileDownloaderState();
}
class _FileDownloaderState extends State<FileDownloader> {
final pdfUrl = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
bool downloading = false;
var progress = "";
var path = "No Data";
var platformVersion = "Unknown";
var _onPressed;
Directory externalDir;
#override
void initState() {
super.initState();
downloadFile();
}
String convertCurrentDateTimeToString() {
String formattedDateTime =
DateFormat('yyyyMMdd_kkmmss').format(DateTime.now()).toString();
return formattedDateTime;
}
Future<void> downloadFile() async {
Dio dio = Dio();
final status = await Permission.storage.request();
if (status.isGranted) {
String dirloc = "";
if (Platform.isAndroid) {
dirloc = "/sdcard/download/";
} else {
dirloc = (await getApplicationDocumentsDirectory()).path;
}
try {
FileUtils.mkdir([dirloc]);
await dio.download(pdfUrl, dirloc + convertCurrentDateTimeToString() + ".pdf",
onReceiveProgress: (receivedBytes, totalBytes) {
print('here 1');
setState(() {
downloading = true;
progress = ((receivedBytes / totalBytes) * 100).toStringAsFixed(0) + "%";
print(progress);
});
print('here 2');
});
} catch (e) {
print('catch catch catch');
print(e);
}
setState(() {
downloading = false;
progress = "Download Completed.";
path = dirloc + convertCurrentDateTimeToString() + ".pdf";
});
print(path);
print('here give alert-->completed');
} else {
setState(() {
progress = "Permission Denied!";
_onPressed = () {
downloadFile();
};
});
}
}
#override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text('File Downloader'),
),
body: Center(
child: downloading
? Container(
height: 120.0,
width: 200.0,
child: Card(
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
SizedBox(
height: 10.0,
),
Text(
'Downloading File: $progress',
style: TextStyle(color: Colors.white),
),
],
),
),
)
: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(path),
MaterialButton(
child: Text('Request Permission Again.'),
onPressed: _onPressed,
disabledColor: Colors.blueGrey,
color: Colors.pink,
textColor: Colors.white,
height: 40.0,
minWidth: 100.0,
),
],
)));
}

Add progress bar in flutter when open pdf file from url

I have a problem and I cannot solve it and I did not find a source to solve it on Google, I have a page where I view a PDF file through a link, and I have a CircularProgressIndicator and I want to replace it with a progress bar showing the percentage of downloading the file, can I do that?
I have attached my code
import 'package:flutter/material.dart';
import 'package:flutter_plugin_pdf_viewer/flutter_plugin_pdf_viewer.dart';
class ReadPdf extends StatefulWidget {
final String value;
ReadPdf({Key key, this.value}) : super(key: key);
#override
_ReadPdfState createState() => _ReadPdfState();
}
class _ReadPdfState extends State<ReadPdf>{
bool _isloading = false, _isInit = true;
PDFDocument document;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
body: Container(
child: Column(
children: <Widget>[
Expanded(child:Center(
child: _isInit? MaterialButton(child: Text('Go'), onPressed: () {_loadFromURL(widget.value);},
color: Color.fromRGBO(64, 75, 96, .9),
textColor: Colors.white,
) : _isloading? Center(child: CircularProgressIndicator(),) : PDFViewer(document: document,indicatorBackground: Colors.deepPurple,),
),),
Row(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
],
),
],
),
),
),
);
}
_loadFromURL(String url) async{
setState(() {
_isInit = false;
_isloading = true;
});
document = await PDFDocument.fromURL('${url}'); setState(() {
_isloading = false;
});
}
}
I have an app with the same feature, I used Dio this package supports downloading a file to your phone.
All you need to do is
Dio dio = Dio();
dio.download("*YOUR URL WHERE YOU WANT TO DOWNLOAD A FILE*",
"*YOUR DESTINATION PATH*", onReceiveProgress: (rec, total) {
print("Downloading " + ((rec / total) * 100).toStringAsFixed(0) + "%");
});
Never used this for pdf, but I've tried it for NetworkImage().
Not sure if it'll help. But you can just try it if there's a way to use loadingBuilder in your code.
Image.network(
imageUrl,
fit: BoxFit.cover,
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent loadingProgress) {
if (loadingProgress == null)
return child;
else {
return Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes
: null,
),
);
}
},
);
u can use flutter_cached_pdfview
and this an example to view a pdf from URL and cache it with placeholder
u can replace placeholder with any widget like CircularProgressIndicator
PDF().cachedFromUrl(
'http://africau.edu/images/default/sample.pdf',
placeholder: (progress) => Center(child: Text('$progress %'))
)
take a look https://pub.dev/packages/flutter_cached_pdfview

how to download and save a file from internet to the internal storage(android) in Flutter/dart?

i need to save file eg.jpg to "internalstorage/appname/files/"
and show a notification if it does exists already in folder. when a button is pressed/activity intiated,it should download file to local storage of andorid device with dart code.
help me find solution.
**code:**
import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import './landing_page.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:simple_permissions/simple_permissions.dart';
import 'package:flutter/services.dart';
class MoviesPage extends StatefulWidget {
#override
State createState() => new MoviesPageState();
}
class MoviesPageState extends State<MoviesPage> {
final dUrl ="https://cdn.putlockers.es/download/0BBCA7584749D4E741747E32E6EB588AEA03E40F";
bool downloading = false;
var progressString = "";
static const MethodChannel _channel =
const MethodChannel('flutter_downloader');
#override
void initState() {
super.initState();
downloadFile();
}
Future<void> downloadFile() async {
Dio dio = Dio();
try {
var dir = await getApplicationDocumentsDirectory();
await dio.download(dUrl, "${dir.path}/file.torrent",
onProgress: (rec, total) {
print("Rec: $rec , Total: $total");
setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
});
} catch (e) {
print(e);
}
setState(() {
downloading = false;
progressString = "Completed";
});
print("Download completed");
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("AppBar"),
),
body: Center(
child: downloading
? Container(
height: 120.0,
width: 200.0,
child: Card(
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
SizedBox(
height: 20.0,
),
Text(
"Downloading File: $progressString",
style: TextStyle(
color: Colors.white,
),
)
],
),
),
)
: Text("No Data"),
),
);
}
}
thanks in advance.post your solutions in full fludged manner.
I've checked the minimal repro you've posted and it seems that you're using Flutter plugin dio to download the file. I've reused the Future<void> downloadFile() from your code and modified it a bit to check if the plugin works as expected. As of version 3.0.10 of the dio plugin, the onProgress on dio.download() is now onReceiveProgress, but it still essentially has the same function.
Here's the method for downloading the image file based from your code with a bit of modification.
Future downloadFile() async {
Dio dio = Dio();
var dir = await getApplicationDocumentsDirectory();
var imageDownloadPath = '${dir.path}/image.jpg';
await dio.download(imageSrc, imageDownloadPath,
onReceiveProgress: (received, total) {
var progress = (received / total) * 100;
debugPrint('Rec: $received , Total: $total, $progress%');
setState(() {
downloadProgress = received.toDouble() / total.toDouble();
});
});
// downloadFile function returns path where image has been downloaded
return imageDownloadPath;
}
The plugin works as expected and successfully downloads the image file. Though I'm unable to verify how you're able to determine that the image that you're trying to download fails on your repro. In my sample app, Future downloadFile() returns a String where the image path is stored. I then use this to update the Image Widget to display the downloaded image - this determines that the download has been successful.
Here's the complete sample app.
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final imageSrc = 'https://picsum.photos/250?image=9';
var downloadPath = '';
var downloadProgress = 0.0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(flex: 5, child: Image.network(imageSrc)),
Expanded(
flex: 2,
child: Row(
children: [
ElevatedButton(
// Download displayed image from imageSrc
onPressed: () {
downloadFile().catchError((onError) {
debugPrint('Error downloading: $onError');
}).then((imagePath) {
debugPrint('Download successful, path: $imagePath');
displayDownloadImage(imagePath);
});
},
child: Text('Download'),
),
ElevatedButton(
// Delete downloaded image
onPressed: () {
deleteFile().catchError((onError) {
debugPrint('Error deleting: $onError');
}).then((value) {
debugPrint('Delete successful');
});
},
child: Text('Clear'),
)
],
),
),
LinearProgressIndicator(
value: downloadProgress,
),
Expanded(
flex: 5,
child: downloadPath == ''
// Display a different image while downloadPath is empty
// downloadPath will contain an image file path on successful image download
? Icon(Icons.image)
: Image.file(File(downloadPath))),
],
),
),
);
}
displayDownloadImage(String path) {
setState(() {
downloadPath = path;
});
}
Future deleteFile() async {
final dir = await getApplicationDocumentsDirectory();
var file = File('${dir.path}/image.jpg');
await file.delete();
setState(() {
// Clear downloadPath on file deletion
downloadPath = '';
});
}
Future downloadFile() async {
Dio dio = Dio();
var dir = await getApplicationDocumentsDirectory();
var imageDownloadPath = '${dir.path}/image.jpg';
await dio.download(imageSrc, imageDownloadPath,
onReceiveProgress: (received, total) {
var progress = (received / total) * 100;
debugPrint('Rec: $received , Total: $total, $progress%');
setState(() {
downloadProgress = received.toDouble() / total.toDouble();
});
});
// downloadFile function returns path where image has been downloaded
return imageDownloadPath;
}
}
In the sample app, clicking the 'Download' button will have the network image displayed at the top portion of the screen downloaded. After the download is successful, the downloaded image will be displayed using Image.file() at the lower portion of the screen.

Categories

Resources