Error opening PDF file after downloading from server Flutter

Viewed 217

Hello I have a screen in the app that downloads a PDF file and displays the download progress in percent. After downloading, the file is opened using the package of pdf_render: ^ 1.0.10. Sometimes it opens and displays the PDF file and sometimes it does not open the file and I have a blank screen. I have no fault in the console and I do not know what the fault is. Thank you Flutter App :

class Web_view_vehicle extends StatefulWidget {
  var choice ;
  var name_vehicle;
  Web_view_vehicle({ required this.choice , this.name_vehicle}) : super();
  @override
  _Web_view_vehicleState createState() => _Web_view_vehicleState();
}

class _Web_view_vehicleState extends State<Web_view_vehicle> {

  bool downloading = false;
  String progressString = "";
  String path = '';
  late List data ;


  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/teste.pdf');
  }

  Future<File> writeCounter(Uint8List stream) async {
    final file = await _localFile;

    // Write the file
    return file.writeAsBytes(stream);
  }

  Future<Uint8List> fetchPost() async {
    Dio dio = Dio();
      var response =  await dio.get(widget.choice,
          onReceiveProgress: (rec, total) {
            print("Rec: $rec , Total: $total");
            if(!mounted)return;
            setState(() {
              downloading = true;
              progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
            });
          },options: Options(responseType: ResponseType.bytes));
      final responseJson = response.data;
    if (!mounted) {
    }
    setState(() {
      downloading = false;
      progressString = "Completed";
    });
    print("Download completed");
    return responseJson;
  }

  loadPdf() async {
    writeCounter((await fetchPost()));
    path = (await _localFile).path;
    if (!mounted) return;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    loadPdf();

  }

  @override
  Widget build(BuildContext context) {

    Color? bgColor = Colors.grey[300];

    return Scaffold(
        backgroundColor: bgColor,
        appBar: AppBar(
          leading: Padding(
            padding: const EdgeInsets.fromLTRB(5.0 , 0.0 , 0.0 , 0.0),
            child: new IconButton(
                icon: new Icon(Icons.arrow_back),
                onPressed: (){Navigator.pop(context,true);}
            ),
          ),
          title: Text('מדריך לרכב ${widget.name_vehicle}',textAlign: TextAlign.center,textDirection: TextDirection.rtl,),
          backgroundColor: Colors.red[400],
          centerTitle: true,
          actions: <Widget>[

          ],
        ),

        body:
        (path.length > 5)?
        PdfViewer.openFile(path,
    ):
        Center(child: Column(crossAxisAlignment: CrossAxisAlignment.center,mainAxisAlignment: MainAxisAlignment.center,mainAxisSize: MainAxisSize.max,
      children: [
        CircularProgressIndicator(),
      Text('טוען מדריך ${progressString}',textDirection: TextDirection.rtl,textAlign: TextAlign.center,)
      ],
    ))

        );
  }


}
0 Answers
Related