Open In App

Flutter - Check Internet Download Speed Programmatically

Last Updated : 21 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Flutter, we can check the network speed programmatically by making HTTP requests and measuring the time it takes to download a small file. There is a small formula to calculate the download speed of the internet connection.

final speedInKbps = ((response.bodyBytes.length / 1024) / (elapsed / 1000)) * 8;
  • First, we make an HTTP request using an HTTP Package request to a URL to download a file.
  • Then we start a stopwatch to measure the time, The elapsed time in milliseconds (the time it took to download the file) is recorded using the stopwatch.
  • The size of the downloaded file is obtained using response.bodyBytes.length. It is divided by 1024 to convert it from bytes to kilobytes.
  • The download speed is calculated by dividing the file size (in KB) by the elapsed time (in seconds) to get the speed in kilobytes per second (KBps).
  • To convert the speed from KBps to kilobits per second (Kbps), the result is multiplied by 8.

In this article, we are going to check the download speed of our Internet connection programmatically by creating a Flutter application.

Step-by-Step Implementation

Step 1: Create a New Flutter Application

Create a new Flutter application using the command Prompt. To create a new app, write the below command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter.

Step 2: Adding the Dependency

To add the dependency to the pubspec.yaml file, add  http as a dependency in the dependencies part of the pubspec.yaml file, as shown below:

Dart
dependencies:
     flutter:
       sdk: flutter
     http: ^1.3.0


Now run the below command in the terminal.

flutter pub get

Or

Run the below command in the terminal.

flutter pub add http


Step 3 : Import dependencies

To use libraries, import all of them in the respective .dart file,

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


Step 4: Execute the main Method

Here the execution of our app starts.

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


Step 5: Create MyApp Class

In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.

Dart
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home:NetworkSpeedChecker(),
    );
  }
}


Step 6: Create NetworkSpeedChecker Class

This class contains a Future method named as checkNetworkSpeed which is responsible for calculating the Internet download speed.

  • It makes an HTTP GET request to a specified URL, which is a file to be downloaded.
  • It measures the time taken to download the file using a stopwatch.
  • If the HTTP response status code is 200 (referring a successful download), it calculates the download speed in Kbps (kilobits per second).
  • It then displays an Alert Dialog containing the download speed if the download was successful.
  • If the download fails or the response status code is not 200, it shows an error message in an Alert Dialog.
  • In case of any exception or error during the process, it displays an error message in an Alert Dialog as well.

Then in this build method we created a ElevatedButton by clicking which we call the above checkNetworkSpeed method and display the speed in a Alert Dialog. Comments are added for better understanding.

checkNetworkSpeed() Method:

Dart
// Function to check network speed(Future Method)
Future<void> checkNetworkSpeed(BuildContext context) async {
  final url =
      'https://drive.google.com/file/d/1lEn1DtJQW6-nTcoS_FG7-EB3Kamy0147/view?usp=sharing';
  final stopwatch = Stopwatch()..start();

  try {
    final response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
      final elapsed = stopwatch.elapsedMilliseconds;
      final speedInKbps =
          ((response.bodyBytes.length / 1024) / (elapsed / 1000)) *
          8; // Calculate download speed in Kbps

      // Show download speed in an AlertDialog
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            // Set the dialog title
            title: Text('Network Speed'),
            // Display download speed
            content: Text(
              'Download speed: ${speedInKbps.toStringAsFixed(2)} Kbps',
            ),
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                // Button to close the dialog
                child: Text('OK'),
              ),
            ],
          );
        },
      );
    } else {
      // Show an error dialog if the download failed
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            // Set the error dialog title
            title: Text('Error'),
            // Display error message
            content: Text(
              'Failed to download the file. Status code: ${response.statusCode}',
            ),
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                // Button to close the dialog
                child: Text('OK'),
              ),
            ],
          );
        },
      );
    }
  } catch (e) {
    // Show an error dialog in case of an exception
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          // Set the exception dialog title
          title: Text('Error'),
          // Display the exception message
          content: Text('Error: $e'),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              // Button to close the dialog
              child: Text('OK'),
            ),
          ],
        );
      },
    );
  }
}


Complete Source Code

main.dart:

Dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: NetworkSpeedChecker(),
    );
  }
}

class NetworkSpeedChecker extends StatelessWidget {
  
  // Function to check network speed(Future Method)
  Future<void> checkNetworkSpeed(BuildContext context) async {
    final url =
        'https://drive.google.com/file/d/1lEn1DtJQW6-nTcoS_FG7-EB3Kamy0147/view?usp=sharing';
    final stopwatch = Stopwatch()..start();

    try {
      final response = await http.get(Uri.parse(url));

      if (response.statusCode == 200) {
        final elapsed = stopwatch.elapsedMilliseconds;
        
        // Calculate download speed in Kbps
        final speedInKbps = ((response.bodyBytes.length / 1024) / (elapsed / 1000)) * 8; 

        // Show download speed in an AlertDialog
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
                
              // Set the dialog title
              title: Text('Network Speed'),
              
              // Display download speed
              content: Text(
                'Download speed: ${speedInKbps.toStringAsFixed(2)} Kbps',
              ),
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  
                  // Button to close the dialog
                  child: Text('OK'),
                ),
              ],
            );
          },
        );
      } else {
        
        // Show an error dialog if the download failed
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              
              // Set the error dialog title
              title: Text('Error'),
              
              // Display error message
              content: Text(
                'Failed to download the file. Status code: ${response.statusCode}',
              ),
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  
                  // Button to close the dialog
                  child: Text('OK'),
                ),
              ],
            );
          },
        );
      }
    } catch (e) {
      
      // Show an error dialog in case of an exception
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            
            // Set the exception dialog title
            title: Text('Error'),
            
            // Display the exception message
            content: Text('Error: $e'),
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                
                // Button to close the dialog
                child: Text('OK'),
              ),
            ],
          );
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Network Download Speed Checker'),
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
      ),
      body: Center(
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.green,
            foregroundColor: Colors.white,
            shape: RoundedRectangleBorder(
                
              // Rounded corners
              borderRadius: BorderRadius.circular(5), 
            ),
          ),
          onPressed: () {
              
            // Trigger the network speed check when the button is pressed
            checkNetworkSpeed(context);
          },
          
          // Button text
          child: Text('Check Network Speed'), 
        ),
      ),
    );
  }
}


Output:



Next Article

Similar Reads