Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel file download with http response in Flutter

I need to cancel download process while file downloading.

final http.Response responseData =
        await http.get("URL_HEAR");

How can I stop/abort current running download file. I am newbie in flutter. Can anyone help me out this.

like image 254
Jay Nirmal Avatar asked Jan 30 '26 08:01

Jay Nirmal


1 Answers

http.get is just a convenience function that creates and underlying Client, performs the get on that and then calls close on the client.

If you create a client, you can call close on that during a get and it will cancel. Here's an example showing how to create, use and close a client, together with a timer to demonstrate an early close cancelling the get.

import 'dart:async';

import 'package:http/http.dart' as http;

void main() async {
  // create a Client
  final client = http.Client();

  // Start a timer to demonstrate calling close() while in operation
  Timer(Duration(seconds: 1), () {
    client.close();
  });

  // use client.get as you would http.get
  final response = await client.get(
    Uri.parse('http://ipv4.download.thinkbroadband.com/100MB.zip'),
  );

  print(response.body.length); // this line is not reached

  // don't forget to close() the client for sunny day when *not* cancelled
  client.close();
}
like image 61
Richard Heap Avatar answered Feb 01 '26 14:02

Richard Heap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!