Flutter网络速度测试插件flutter_internet_speed_test的使用
Flutter网络速度测试插件flutter_internet_speed_test的使用
插件介绍
Flutter Internet Speed Test
是一个用于测试互联网下载和上传速度的Flutter插件。它支持两种服务器:
- Fast.com by Netflix (默认)
- Speed Test by Ookla
该插件适用于iOS和Android平台。
开始使用
添加依赖
在pubspec.yaml
文件中添加以下依赖项:
dependencies:
flutter_internet_speed_test: ^latest_version
请确保将latest_version
替换为实际的最新版本号。
示例代码
下面是一个完整的示例,展示了如何使用此插件来测试网络速度,并显示测试结果。
import 'package:flutter/material.dart';
import 'package:flutter_internet_speed_test/flutter_internet_speed_test.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final internetSpeedTest = FlutterInternetSpeedTest()..enableLog();
bool _testInProgress = false;
double _downloadRate = 0;
double _uploadRate = 0;
String _downloadProgress = '0';
String _uploadProgress = '0';
int _downloadCompletionTime = 0;
int _uploadCompletionTime = 0;
bool _isServerSelectionInProgress = false;
String? _ip;
String? _asn;
String? _isp;
String _unitText = 'Mbps';
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
reset();
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter Internet Speed Test Example'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Download Speed',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
Text('Progress: $_downloadProgress%'),
Text('Download Rate: $_downloadRate $_unitText'),
if (_downloadCompletionTime > 0)
Text(
'Time taken: ${(_downloadCompletionTime / 1000).toStringAsFixed(2)} sec(s)'),
],
),
const SizedBox(
height: 32.0,
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Upload Speed',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
Text('Progress: $_uploadProgress%'),
Text('Upload Rate: $_uploadRate $_unitText'),
if (_uploadCompletionTime > 0)
Text(
'Time taken: ${(_uploadCompletionTime / 1000).toStringAsFixed(2)} sec(s)'),
],
),
const SizedBox(
height: 32.0,
),
Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: Text(_isServerSelectionInProgress
? 'Selecting Server...'
: 'IP: ${_ip ?? '--'} | ASN: ${_asn ?? '--'} | ISP: ${_isp ?? '--'}'),
),
if (!_testInProgress) ...{
ElevatedButton(
child: const Text('Start Testing'),
onPressed: () async {
reset();
await internetSpeedTest.startTesting(
onStarted: () {
setState(() => _testInProgress = true);
},
onCompleted: (TestResult download, TestResult upload) {
setState(() {
_downloadRate = download.transferRate;
_unitText = download.unit == SpeedUnit.kbps ? 'Kbps' : 'Mbps';
_downloadProgress = '100';
_downloadCompletionTime = download.durationInMillis;
});
setState(() {
_uploadRate = upload.transferRate;
_unitText = upload.unit == SpeedUnit.kbps ? 'Kbps' : 'Mbps';
_uploadProgress = '100';
_uploadCompletionTime = upload.durationInMillis;
_testInProgress = false;
});
},
onProgress: (double percent, TestResult data) {
setState(() {
_unitText = data.unit == SpeedUnit.kbps ? 'Kbps' : 'Mbps';
if (data.type == TestType.download) {
_downloadRate = data.transferRate;
_downloadProgress = percent.toStringAsFixed(2);
} else {
_uploadRate = data.transferRate;
_uploadProgress = percent.toStringAsFixed(2);
}
});
},
onError: (String errorMessage, String speedTestError) {
reset();
},
onDefaultServerSelectionInProgress: () {
setState(() {
_isServerSelectionInProgress = true;
});
},
onDefaultServerSelectionDone: (Client? client) {
setState(() {
_isServerSelectionInProgress = false;
_ip = client?.ip;
_asn = client?.asn;
_isp = client?.isp;
});
},
onDownloadComplete: (TestResult data) {
setState(() {
_downloadRate = data.transferRate;
_unitText = data.unit == SpeedUnit.kbps ? 'Kbps' : 'Mbps';
_downloadCompletionTime = data.durationInMillis;
});
},
onUploadComplete: (TestResult data) {
setState(() {
_uploadRate = data.transferRate;
_unitText = data.unit == SpeedUnit.kbps ? 'Kbps' : 'Mbps';
_uploadCompletionTime = data.durationInMillis;
});
},
onCancel: () {
reset();
},
);
},
)
} else ...{
const CircularProgressIndicator(),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextButton.icon(
onPressed: () => internetSpeedTest.cancelTest(),
icon: const Icon(Icons.cancel_rounded),
label: const Text('Cancel'),
),
)
},
],
),
),
),
);
}
void reset() {
setState(() {
_testInProgress = false;
_downloadRate = 0;
_uploadRate = 0;
_downloadProgress = '0';
_uploadProgress = '0';
_unitText = 'Mbps';
_downloadCompletionTime = 0;
_uploadCompletionTime = 0;
_ip = null;
_asn = null;
_isp = null;
});
}
}
其他特性
- 自定义服务器URL:您可以配置自己的测试服务器URL。
- 文件大小设置:可以指定要测试的文件大小。
- 错误处理:提供了详细的错误回调函数以处理可能出现的问题。
如果您不提供自定义的服务器URL,插件将使用默认的服务器:
- 下载测试服务器:
https://fast.com/
或http://speedtest.ftp.otenet.gr/files/test1Mb.db
- 上传测试服务器:
https://fast.com/
或http://speedtest.ftp.otenet.gr/
通过上述步骤,您应该能够顺利地集成并使用flutter_internet_speed_test
插件进行网络速度测试。
更多关于Flutter网络速度测试插件flutter_internet_speed_test的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter网络速度测试插件flutter_internet_speed_test的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用flutter_internet_speed_test
插件来进行网络速度测试的示例代码。这个插件允许你测试下载和上传速度。
首先,你需要在你的pubspec.yaml
文件中添加依赖:
dependencies:
flutter:
sdk: flutter
flutter_internet_speed_test: ^0.4.0 # 请检查最新版本号
然后运行flutter pub get
来安装依赖。
接下来,在你的Flutter应用中,你可以按照以下步骤使用flutter_internet_speed_test
插件:
- 导入插件:
在你的Dart文件中导入插件:
import 'package:flutter_internet_speed_test/flutter_internet_speed_test.dart';
- 测试网络速度:
你可以使用InternetSpeedTest
类的startDownloadTest
和startUploadTest
方法来分别测试下载和上传速度。以下是一个完整的示例,展示如何进行速度测试并显示结果:
import 'package:flutter/material.dart';
import 'package:flutter_internet_speed_test/flutter_internet_speed_test.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String downloadSpeed = '';
String uploadSpeed = '';
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Network Speed Test'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () async {
setState(() {
downloadSpeed = 'Testing...';
});
final downloadResult = await InternetSpeedTest().startDownloadTest(
url: 'https://speedtest.tele2.net/10MB.zip', // 测试文件的URL
onData: (data) {
// 这里可以显示下载进度
print('Download Progress: ${data.progress}%');
},
);
setState(() {
downloadSpeed = '${downloadResult.speed.toStringAsFixed(2)} Mbps';
});
},
child: Text('Test Download Speed'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
setState(() {
uploadSpeed = 'Testing...';
});
final uploadResult = await InternetSpeedTest().startUploadTest(
bytes: Uint8List.fromList(List.filled(10 * 1024 * 1024, 0)), // 10MB的数据
onData: (data) {
// 这里可以显示上传进度
print('Upload Progress: ${data.progress}%');
},
);
setState(() {
uploadSpeed = '${uploadResult.speed.toStringAsFixed(2)} Mbps';
});
},
child: Text('Test Upload Speed'),
),
SizedBox(height: 20),
Text('Download Speed: $downloadSpeed'),
Text('Upload Speed: $uploadSpeed'),
],
),
),
),
);
}
}
在这个示例中,我们创建了一个简单的Flutter应用,其中有两个按钮分别用于测试下载和上传速度。点击按钮后,应用会开始测试并显示速度结果。
startDownloadTest
方法接受一个URL参数,用于下载测试文件。startUploadTest
方法接受一个字节数组参数,用于上传测试数据。
你可以根据需要调整URL和字节数组的大小。测试进度可以通过onData
回调获取,这里我们简单地打印了进度百分比。
希望这个示例对你有帮助!