簡體   English   中英

嘗試使用 Flutter 從 Firebase 下載 PDF

[英]Trying to Download an PDF from Firebase using Flutter

我正在學習如何使用 Flutter,在這個 .app 中,我試圖從final imgUrl = manuais.data()['documento'];下載 PDF 文件final imgUrl = manuais.data()['documento']; < 我用來從 Firebase 數據庫獲取鏈接的最終 imgURL。

這是錯誤:

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)

這是 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)
);

因為你使用我的包flutter_cached_pdfview

你不需要自己下載pdf文件

包可以下載文件,緩存它並查看

 PDF().cachedFromUrl('your download link'),

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM