Cancel file download with http response in Flutter

262

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();
}
Share:
262
Jay Nirmal
Author by

Jay Nirmal

Updated on December 30, 2022

Comments

  • Jay Nirmal
    Jay Nirmal over 1 year

    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.