flutter-download file pdf from URL with dio

Viewed 4980

good morning, i'm new in flutter, i want to use package dio to download pdf file from url with button. but when i click the button nothing happens/no notification about download file in my smartphone (but the file was successfully downloaded and saved in data/com.example.button/files). how can I display a notification on my smartphone about the download progress. the following is the code of the button. thank you so much

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart' as path;

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  // This widget is the root of your application.
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Stack(
                alignment: Alignment.topCenter,
                children: <Widget>[
                  Container(
                    height: 400,
                    width: double.infinity,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.only(
                            bottomLeft: Radius.circular(50),
                            bottomRight: Radius.circular(50))),
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 20),
                      child: Column(
                        children: <Widget>[
                          SizedBox(
                            height: 27,
                          ),
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Expanded(
                                  child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  SizedBox(height: 5),
                                  SizedBox(height: 20),
                                  Container(
                                    width: 150,
                                    child: ElevatedButton(
                                      style: ButtonStyle(
                                          shape: MaterialStateProperty.all<
                                                  RoundedRectangleBorder>(
                                              RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          18.0),
                                                  side: BorderSide()))),
                                      onPressed: () {
                                        downloadBook(
                                            downloadLink:
                                                "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
                                            title: "test");
                                      },
                                      child: Text(
                                        "Download",
                                        style: TextStyle(color: Colors.white),
                                      ),
                                    ),
                                  ),
                                ],
                              )),
                            ],
                          )
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

and here is the code from the downloadBook method

downloadBook({String? downloadLink, String? title}) async {
 
  var dio;
  if (await Permission.storage.request().isGranted) {
   
    final downloadPath = await path.getExternalStorageDirectory();
    var filePath = downloadPath!.path + '/$title.pdf';
   
    dio = Dio();
    await dio.download(downloadLink, filePath).then((value) {
    
      dio.close();
    }).catchError((Object e) {
    
      Fluttertoast.showToast(
          msg: "Terjadi kesalahan. Download gagal.", timeInSecForIosWeb: 1);
    });
  } else {
   
  }
}

and here is the code from the androidmanifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.simple_stratik">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application android:label="BPS-Simpel Stratik" android:icon="@mipmap/ic_launcher" android:usesCleartextTraffic="true">
        <activity android:name=".MainActivity" android:launchMode="singleTop" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize">
            <!--
            Specifies an Android theme to apply to this Activity as soon as
            the Android process has started. This theme is visible to the user
            while the Flutter UI initializes. After that, this theme continues
            to determine the Window background behind the Flutter UI.
            -->
            <meta-data android:name="io.flutter.embedding.android.NormalTheme" android:resource="@style/NormalTheme" />
            <!--
            Displays an Android View that continues showing the launch screen
            Drawable until Flutter paints its first frame, then this splash
            screen fades out. A splash screen is useful to avoid any visual
            gap between the end of Android's launch screen and the painting of
            Flutter's first frame.
            -->
            <meta-data android:name="io.flutter.embedding.android.SplashScreenDrawable" android:resource="@drawable/launch_background" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!--
        Don't delete the meta-data below.
        This is used by the Flutter tool to generate GeneratedPluginRegistrant.java
        -->
        <meta-data android:name="flutterEmbedding" android:value="2" />
    </application>
</manifest>
1 Answers

There are some ways that you can display the progress you are making when downloading some files. One of it is by using the plugin flutter_local_notifications. It is a cross platform plugin for displaying local notifications. Check the working example in this SO post. Another plugins that could make this possible is using flutter_downloader as mentioned in the comment section, you can check the detailed example here. Some plugin might as well be essential like the percent_indicator plugin. You can either add Linear percent indicators under your download button while downloading or just replace the whole thing with Circular percent indicators.

Related