Im triying to load a pdf file and render it in screen with the following code:
import 'package:flutter/material.dart';
import 'package:pdf_viewer_plugin/pdf_viewer_plugin.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:io';
import 'dart:developer';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
FileLoad createState() => FileLoad();
}
class FileLoad extends State<MyApp> {
String _filePath = "";
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test PDF',
theme: ThemeData(primarySwatch: Colors.blue,),
home:
Scaffold(
backgroundColor: Colors.grey,
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: "Home"),
BottomNavigationBarItem(icon: Icon(Icons.folder), label: "Load File")
],
onTap: (int index) async {
var go = 1;
if (index == 1) {
var status = await Permission.storage.status;
if (status != PermissionStatus.granted) {
var result = await Permission.storage.request();
if (result != PermissionStatus.granted) {
go = 0;
}
}
if (go == 1) {
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path!);
setState(() {
_filePath = file.path;
log('_filePath: $_filePath');
});
}
}
}
},
),
body:
PdfView(path: _filePath, gestureNavigationEnabled: true,)
)
);
}
I can see the log with the correct filepath selected in the explorer, but nothing is rendered in the screen. What is wrong with the code?
Any error is triggered in the console.
For me it looks like that the PdfView itself doesn't load the newest path even with a setState(). I had this problem with other PDF-Viewer plugins.
I solved it by wrapping the PDFView into a if statement and while there is no path loaded some sort of loading Widget is displayed.
Like so:
String? _filePath;
body:
_filePath != null ? PdfView(path: _filePath, gestureNavigationEnabled: true,): Text("loading")
Related
I wrote this code recently but it doesn't get me the result!
import 'package:flutter/material.dart';
import 'package:http/http.dart' show get;
import 'package:pics/src/widgets/image_list.dart';
import 'models/image_model.dart';
import 'dart:convert';
class App extends StatefulWidget {
createState() {
return AppState();
}
}
class AppState extends State<App> {
int counter = 0;
List<ImageModel> images = [];
void fetchImage() async {
counter++;
final Uri rep =
Uri.parse('https://jsonplaceholder.typicode.com/photos/$counter');
var response = await get(rep);
var imageModel = ImageModel.fromJson(json.decode(response.body));
setState(() {
images.add(imageModel);
});
}
Widget build(context) {
return MaterialApp(
home: Scaffold(
body: ImageList(images),
appBar: AppBar(
title: const Text('Lets see some images'),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: fetchImage,
),
),
);
}
}
The terminal say this:
The following NetworkImageLoadException was thrown resolving an image
codec: HTTP request failed, statusCode: 403,
https://via.placeholder.com/600/92c952
When the exception was thrown, this was the stack:
#0 NetworkImage._loadAsync (package:flutter/src/painting/_network_image_io.dart:117:9)
Image provider: NetworkImage("https://via.placeholder.com/600/92c952",
scale: 1.0) Image key:
NetworkImage("https://via.placeholder.com/600/92c952", scale: 1.0)
and this is image list class if you need to read it:
import 'package:flutter/material.dart';
import '../models/image_model.dart';
class ImageList extends StatelessWidget {
final List<ImageModel> images;
ImageList(this.images);
Widget build(context) {
return ListView.builder(
itemCount: images.length,
itemBuilder: (context, int index) {
return Image.network(images[index].url);
},
);
}
}
and this is Image Model:
class ImageModel {
late int id;
late String title;
late String url;
ImageModel(this.id, this.title, this.url);
ImageModel.fromJson(Map<String, dynamic> parsedJson) {
id = parsedJson['id'];
title = parsedJson['title'];
url = parsedJson['url'];
}
}
You can use web render, run with --web-renderer html
flutter run -d c --web-renderer html
-d to select device, where c is chrome
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 am new to flutter. Currently i am building the web app that using flutter webview plugin but i have a question about the internet connectivity. When users doesnt have a connection that app gives a default error page like
Webpage not available
The webpage at https://covid19.who.int/ could be not be loaded because:
net:::ERR_Internet_disconnected
How to use custom code to show custom error page like to hide url? My proper code is:
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:covidwho/layout/myAppBar.dart';
class Who extends StatefulWidget {
#override
_WhoState createState() => _WhoState();
}
class _WhoState extends State<Who> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar(),
body: Container(
child: WebviewScaffold(
url: "https://covid19.who.int/",
withJavascript: true,
withLocalStorage: true,
hidden: true,
initialChild: Container(
color: Colors.white,
child: const Center(
child: CircularProgressIndicator(
backgroundColor: Colors.black,
),
)),
),
),
);
}
}
I would like to share with you the code I use to show custom pages at the time of flutter web errors.
Full project link https://github.com/K3rimoff/flutter-custom-web-error-page
import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import '../../components/back_pressed.dart';
import '../../theme/colors.dart';
import '../error/error.dart';
class WebScreen extends StatefulWidget {
const WebScreen({super.key});
#override
State<WebScreen> createState() => _WebScreenState();
}
class _WebScreenState extends State<WebScreen> with TickerProviderStateMixin {
late AnimationController _animationController;
InAppWebViewController? _webViewController;
PullToRefreshController? _refreshController;
bool _isLoading = false, _isVisible = false, _isOffline = false;
// 0 - Everything is ok, 1 - http or other error fixed
int _errorCode = 0;
final BackPressed _backPressed = BackPressed();
Future<void> checkError() async {
//Hide CircularProgressIndicator
_isLoading = false;
//Check Network Status
ConnectivityResult result = await Connectivity().checkConnectivity();
//if Online: hide offline page and show web page
if (result != ConnectivityResult.none) {
if (_isOffline == true) {
_isVisible = false; //Hide Offline Page
_isOffline = false; //set Page type to error
}
}
//If Offline: hide web page show offline page
else {
_errorCode = 0;
_isOffline = true; //Set Page type to offline
_isVisible = true; //Show offline page
}
// If error is fixed: hide error page and show web page
if (_errorCode == 1) _isVisible = false;
setState(() {});
}
#override
void dispose() {
_animationController.dispose();
super.dispose();
}
#override
void initState() {
super.initState();
_animationController =
AnimationController(vsync: this, duration: const Duration(seconds: 2));
_animationController.repeat();
_refreshController = PullToRefreshController(
onRefresh: () => _webViewController!.reload(),
options: PullToRefreshOptions(
color: Colors.white, backgroundColor: Colors.black87),
);
}
#override
Widget build(BuildContext context) {
return WillPopScope(
child: Scaffold(
body: SafeArea(
child: Stack(
alignment: Alignment.center,
children: [
InAppWebView(
onWebViewCreated: (controller) =>
_webViewController = controller,
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
supportZoom: false,
)),
initialUrlRequest: URLRequest(
url: Uri.parse(
"https://google.com")), // For http error: change to wrong url : https://google.com/404/
pullToRefreshController: _refreshController,
onLoadStart: (controller, url) {
setState(() {
_isLoading = true; //Show CircularProgressIndicator
});
},
onLoadStop: (controller, url) {
_refreshController!.endRefreshing();
checkError(); //Check Error type: offline or other error
},
onLoadError: (controller, url, code, message) {
// Show
_errorCode = code;
_isVisible = true;
},
onLoadHttpError: (controller, url, statusCode, description) {
_errorCode = statusCode;
_isVisible = true;
},
),
//Error Page
Visibility(
visible: _isVisible,
child: ErrorScreen(
isOffline: _isOffline,
onPressed: () {
_webViewController!.reload();
if (_errorCode != 0) {
_errorCode = 1;
}
}),
),
//CircularProgressIndicator
Visibility(
visible: _isLoading,
child: CircularProgressIndicator.adaptive(
valueColor: _animationController.drive(
ColorTween(
begin: circularProgressBegin,
end: circularProgressEnd),
),
),
),
],
),
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ElevatedButton.icon(
onPressed: () {
_errorCode = 1;//My Error fixed code
_webViewController!.loadUrl(
urlRequest: URLRequest(
url: Uri.parse("https://google.com/"), //Correct url
),
);
},
label: const Text("Load Correct URL"),
icon: const Icon(Icons.check),
),
ElevatedButton.icon(
onPressed: () {
_webViewController!.loadUrl(
urlRequest: URLRequest(
url: Uri.parse("https://google.com/404"), //Wrong url
),
);
},
label: const Text("Load Wrong URL"),
icon: const Icon(Icons.close),
),
],
),
),
onWillPop: () async {
//If website can go back page
if (await _webViewController!.canGoBack()) {
await _webViewController!.goBack();
return false;
} else {
//Double pressed to exit app
return _backPressed.exit(context);
}
});
}
}
For that you need to implement
Stream<String> onError webview event.
Don't forget to dispose webview flutterWebviewPlugin.dispose()
Here is a code sample
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
String selectedUrl = 'https://flutter.io';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyHomePage());
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// Instance of WebView plugin
final flutterWebViewPlugin = FlutterWebviewPlugin();
// On destroy stream
StreamSubscription _onDestroy;
// On Http error
StreamSubscription<WebViewHttpError> _onHttpError;
final _scaffoldKey = GlobalKey<ScaffoldState>();
#override
void initState() {
super.initState();
flutterWebViewPlugin.launch(selectedUrl);
// Add a listener to on destroy WebView, so you can make came actions.
_onDestroy = flutterWebViewPlugin.onDestroy.listen((_) {
if (mounted) {
// Actions like show a info toast.
_scaffoldKey.currentState.showSnackBar(
const SnackBar(content: const Text('Webview Destroyed')));
}
});
_onHttpError =
flutterWebViewPlugin.onHttpError.listen((WebViewHttpError error) {
if (mounted) {
//do your customization here
}
});
}
#override
void dispose() {
// Every listener should be canceled, the same should be done with this stream.
_onDestroy.cancel();
_onHttpError.cancel();
flutterWebViewPlugin.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
);
}
}
I want to load a layout (mostly images) in the background with cached_network_image in flutter.
I used Splashscreen and this code, but it's not working. Do you have any ideas or maybe a better solution?
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:login/packages/intro_slider.dart';
import 'package:login/packages/splashscreen.dart';
class TestPage extends StatefulWidget{
#override
State<StatefulWidget> createState() => _TestPage();
}
class _TestPage extends State<TestPage>{
List<Slide> slides = new List();
String pageOne = "";
String pageTwo = "";
getData() async{
var userName = "";
final response =
await http.post('http://test.com/api',body: {"something":userName});
if (response.statusCode == 200) {
// If server returns an OK response, Return pinCode
var js = jsonDecode(response.body);
pageOne = js[0]['pic1'].toString();
pageTwo = js[0]['pic2'].toString();
slides.add(
new Slide(
backgroundImage: "https://test.com/pic/" + pageOne,
backgroundOpacity: 0,
),
);
slides.add(
new Slide(
backgroundImage: "https://test.com/pic/" + pageTwo,
backgroundOpacity: 0,
),
);
return await new Future<Widget>.delayed(
new Duration(
seconds: 1
), () => slider()
);
}
}
#override
void initState() {
super.initState();
}
Widget slider(){
return Scaffold(
body: new IntroSlider(
slides: this.slides,
),
);
}
#override
Widget build(BuildContext context) {
return new SplashScreen(
loadingData: getData,
image: new Image.asset("assets/images/logo.png"),
);
}
}
And, I try to cached image in intro_slider:
PinchZoomImage(
image: CachedNetworkImage(
imageUrl: backgroundImage,
),
hideStatusBarWhileZooming: true,
),
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.