checkInternetSpeed method

Future<double?> checkInternetSpeed({
  1. String testUrl = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
  2. Duration timeout = const Duration(seconds: 5),
})

Kiểm tra tốc độ internet (trả về KB/s) Returns null nếu không thể test được

Implementation

Future<double?> checkInternetSpeed({
  String testUrl =
      'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
  Duration timeout = const Duration(seconds: 5),
}) async {
  try {
    final stopwatch = Stopwatch()..start();

    final response = await http.get(Uri.parse(testUrl)).timeout(timeout);

    stopwatch.stop();

    if (response.statusCode == 200) {
      final bytes = response.bodyBytes.length;
      final seconds = stopwatch.elapsedMilliseconds / 1000.0;
      final speedKBps = (bytes / 1024) / seconds;

      return speedKBps;
    }

    return null;
  } catch (e) {
    return null;
  }
}