Show menu

main.dart

  void main() => runApp(DemoApp());

  class DemoApp extends StatelessWidget {
    const DemoApp();

    @override
    Widget build(BuildContext context) {
      return ChangeNotifierProvider<DownloadProgress>(
        create: (_) => DownloadProgress(),
        child: MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: const Text("Download Demo"),
            ),
            body: Center(
              child: const DownloadWidget(),
            )
          )
        ),
      );
    }
  }
  

progress.dart

  class DownloadProgress with ChangeNotifier {

    double get progress => _progress;

    void start({ required String url,  required String localPath}) async {
      // Reset in case it isn't at zero
      _resetProgress();

      // Path and name
      final directory = await getTemporaryDirectory();
      final fileName = "${directory.path}/$localPath";

      // Donwload the file
      await Dio().download(url, fileName,
        options: Options(
          headers: {
            HttpHeaders.acceptEncodingHeader: "*"
          }
        ),
        onReceiveProgress: (received, total) {
          if (total != -1) {
            var pos = received / total * 100;
            _updateProgress(pos);
          }
        }
      );

    }

    double _progress = 0;

    void _resetProgress() {
      if (progress != 0) {
        _progress = 0;
        notifyListeners();
      }
    }

    void _updateProgress(double value) {
      _progress = value;
      notifyListeners();
    }

  }
  

download_widget.dart

  class DownloadWidget extends StatelessWidget {
    final String url = "https://website.com/files/something.pdf";
    const DownloadWidget();

    @override
    Widget build(BuildContext context) {
      return Center(
        child: Consumer<DownloadProgress>(
          builder: (context, status, _) {
            var progress = status.progress.toStringAsFixed(1);

            return RaisedButton(
              child: Text("$progress %"),
              onPressed: () => status.start(url: url,
                localPath: "file_p2.pdf"
              ),
            );
          },
        ),
      );
    }

  }
  

This website and the book are not official Google products. No affiliations are involved. Built with Java 14 and Vert.X

"Flutter and the related logo are trademarks of Google LLC. We are not endorsed by or affiliated with Google LLC"