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;
- First, we make an HTTP 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. 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.
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( 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.
- 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:
// 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
),
],
);
},
);
}
}
Dart
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; 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
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( 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 = '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( // 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 ), ), ); } } |