[英]Trying to Download an PDF from Firebase using Flutter
i'm learning how to use Flutter, and in the this .app i'm trying to download a PDF file from firebase final imgUrl = manuais.data()['documento'];
我正在学习如何使用 Flutter,在这个 .app 中,我试图从
final imgUrl = manuais.data()['documento'];
下载 PDF 文件final imgUrl = manuais.data()['documento'];
< this final imgURL I use to get the link from Firebase Database. < 我用来从 Firebase 数据库获取链接的最终 imgURL。
This is the error:这是错误:
I/flutter (12444): error is
I/flutter (12444): FileSystemException: Cannot open file, path = '/storage/emulated/0/Download/newtask1.pdf' (OS Error: Operation not permitted, errno = 1)
Here is de code这是 de 代码
import 'dart:typed_data';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dio/dio.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'dart:io';
import 'package:flutter_cached_pdfview/flutter_cached_pdfview.dart';
import 'package:permission_handler/permission_handler.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int _currentIndex = 0;
final tabs = [
//TAB DE MANUAIS
Center(
child: (Scaffold(
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection('manuais').snapshots(),
builder: (context, snapshot) {
if (snapshot.data == null) return CircularProgressIndicator();
return Container(
padding: EdgeInsets.all(16),
child: ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot manuais =
snapshot.data.documents[index];
final imgUrl = manuais.data()['documento'];
var dio = Dio();
return Card(
color: Colors.grey[250],
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Image.network(manuais.data()['logo'].toString(), width: 32,
),
Center(
child: Text(
(manuais.data()['nome'].toString()),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 16),
),
),
ButtonBar(
children: <Widget>[
//BOTAO DE DOWNLOAD
FlatButton(
child: const Text('Download'),
onPressed: () async {
String path =
await ExtStorage.getExternalStoragePublicDirectory(
ExtStorage.DIRECTORY_DOWNLOADS);
String fullPath = '$path/newtask1.pdf';
download2(dio, imgUrl, fullPath);
},
),
FlatButton(
child: const Text('Compartilhar'),
onPressed: () async {
if (snapshot.data == null) return CircularProgressIndicator();
var request = await HttpClient().getUrl(Uri.parse(manuais.data()['documento']));
var response = await request.close();Uint8List bytes = await consolidateHttpClientResponseBytes(response);
await Share.file(
'ESYS AMLOG',
'Manual.pdf',
bytes,
'image/jpg');
}),
],
),
],
),
),
);
}),
);
})))),
//TAB DE PRODUCAO
Center(
child: (Scaffold(
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection('producao').snapshots(),
builder: (context, snapshot) {
if (snapshot.data == null) return CircularProgressIndicator();
return Container(
padding: EdgeInsets.all(16),
child: ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot producao =
snapshot.data.documents[index];
return Card(
color: Colors.grey[250],
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Center(
child: Image.network(producao.data()['img'].toString(), width: 260,
),
),
Text(
(producao.data()['data'].toString()),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 22),
),
Text(
(producao.data()['detail'].toString()),
style: TextStyle(fontSize: 16),
),
ButtonBar(
children: <Widget>[
FlatButton(
child: const Text('DETALHES'),
onPressed: () {}),
FlatButton(
child: const Text('COMPARTILHAR'),
onPressed: () async {
if (snapshot.data == null) return CircularProgressIndicator();
var request = await HttpClient().getUrl(Uri.parse(producao.data()['img']));
var response = await request.close();Uint8List bytes = await consolidateHttpClientResponseBytes(response);
await Share.file(
'ESYS AMLOG',
'amlog.jpg',
bytes,
'image/jpg');
}),
],
),
],
),
),
);
}),
);
})))),
Center(child: Text('Documentos')),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Área do Cliente')),
body: tabs[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
type: BottomNavigationBarType.shifting,
iconSize: 28,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.picture_as_pdf),
title: Text('Manuais'),
backgroundColor: Colors.indigo),
BottomNavigationBarItem(
icon: Icon(Icons.build),
title: Text('Produção'),
backgroundColor: Colors.indigo),
BottomNavigationBarItem(
icon: Icon(Icons.folder),
title: Text('Documentos'),
backgroundColor: Colors.indigo,
)
],
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
),
);
}
}
void initState(){
getPermission();
}
void getPermission() async{
print('getPermission');
await PermissionHandler().requestPermissions([PermissionGroup.storage]);
}
Future download2(Dio dio, String url, String savePath) async {
try{
var showDownloadProgress;
Response response = await dio.get(
url,
onReceiveProgress: showDownloadProgress,
options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
validateStatus: (status) {
return status < 500;
}),
);
File file = File(savePath);
var raf = file.openSync(mode: FileMode.write);
raf.writeStringSync(response.data);
await raf.close();
} catch (e) {
print('error is');
print(e);
}
}
```
final taskId = await FlutterDownloader.enqueue(
url: 'your download link',
savedDir: 'directory/your/folder',
showNotification: true, // show download progress in status bar (for Android)
openFileFromNotification: true, // click on notification to open downloaded file (for Android)
);
because u use my package flutter_cached_pdfview因为你使用我的包flutter_cached_pdfview
u don't need to download the pdf file by yourself你不需要自己下载pdf文件
the package can download file, cache it and view包可以下载文件,缓存它并查看
PDF().cachedFromUrl('your download link'),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.