Open In App

Flutter – Check Internet Download Speed Programmatically

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;

In this article, we are going to check the download speed of our Internet connection programmatically by creating a Flutter application. A sample video is given below to get an idea about what we are going to do in this article.



Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Adding the Dependencies

Here we have to add the the following dependencies to our pubspec.yaml file.



dependencies:
http: ^1.1.0

or, simply you can run the following command in your vs code terminal.

flutter pub add http

Step 3: Import the Package

First of all import material.dart package and the http.dart package.

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

Step 4: Execute the main Method

Here the execution of our app starts.




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.




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      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.

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:

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




class NetworkSpeedChecker extends StatelessWidget {
  // Function to check network speed(Future Method)
  Future<void> checkNetworkSpeed(BuildContext context) async {
    final url =
    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(
              title: Text('Network Speed'), // Set the dialog title
              content: Text(
                  // Display download speed
                  'Download speed: ${speedInKbps.toStringAsFixed(2)} Kbps'), 
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('OK'), // Button to close the dialog
                ),
              ],
            );
          },
        );
      } else {
        // Show an error dialog if the download failed
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('Error'), // Set the error dialog title
              content: Text(
                  // Display error message
                  'Failed to download the file. Status code: ${response.statusCode}'), 
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('OK'), // Button to close the dialog
                ),
              ],
            );
          },
        );
      }
    } catch (e) {
      // Show an error dialog in case of an exception
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('Error'), // Set the exception dialog title
            content: Text('Error: $e'), // Display the exception message
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text('OK'), // Button to close the dialog
              ),
            ],
          );
        },
      );
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Network Download Speed Checker'), // Set the app title
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // Trigger the network speed check when the button is pressed
            checkNetworkSpeed(context);
          },
          child: Text('Check Network Speed'), // Button text
        ),
      ),
    );
  }
}

Here is the full Code of main.dart file




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(
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      home:NetworkSpeedChecker(),
    );
  }
}
  
class NetworkSpeedChecker extends StatelessWidget {
  // Function to check network speed(Future Method)
  Future<void> checkNetworkSpeed(BuildContext context) async {
    final url =
    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(
              title: Text('Network Speed'), // Set the dialog title
              content: Text(
                  // Display download speed
                  'Download speed: ${speedInKbps.toStringAsFixed(2)} Kbps'), 
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('OK'), // Button to close the dialog
                ),
              ],
            );
          },
        );
      } else {
        // Show an error dialog if the download failed
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('Error'), // Set the error dialog title
              content: Text(
                  // Display error message
                  'Failed to download the file. Status code: ${response.statusCode}'), 
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('OK'), // Button to close the dialog
                ),
              ],
            );
          },
        );
      }
    } catch (e) {
      // Show an error dialog in case of an exception
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('Error'), // Set the exception dialog title
            content: Text('Error: $e'), // Display the exception message
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text('OK'), // Button to close the dialog
              ),
            ],
          );
        },
      );
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Network Download Speed Checker'), // Set the app title
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // Trigger the network speed check when the button is pressed
            checkNetworkSpeed(context);
          },
          child: Text('Check Network Speed'), // Button text
        ),
      ),
    );
  }
}

Output:


Article Tags :