Flutter网络速度测试插件flutter_speed_test_plus的使用
Flutter网络速度测试插件flutter_speed_test_plus的使用
简介
flutter_speed_test_plus
是一个Flutter插件,用于测量互联网下载和上传速度。它支持使用广泛认可的服务进行测试,如Fast.com(默认)和Ookla的Speedtest。
功能特性
- 测试下载和上传速度。
- 默认支持Fast.com API。
- 可选择自定义测试服务器URL。
- 提供进度跟踪和多个回调函数。
- 支持iOS和Android平台。
截图
开始使用
添加依赖
在 pubspec.yaml
文件中添加插件依赖:
dependencies:
flutter_speed_test_plus: ^latest_version
基本用法
以下是一个简单的示例,展示了如何启动网络速度测试并处理回调:
import 'package:flutter_speed_test_plus/flutter_speed_test_plus.dart';
void startSpeedTest() {
final speedTest = FlutterInternetSpeedTest();
speedTest.startTesting(
useFastApi: true, // 使用Fast.com API,默认为true
onStarted: () {
print('Speed test started');
},
onCompleted: (TestResult download, TestResult upload) {
print('Download Speed: ${download.speed} Mbps');
print('Upload Speed: ${upload.speed} Mbps');
},
onProgress: (double percent, TestResult data) {
print('Progress: $percent%');
},
onError: (String errorMessage, String speedTestError) {
print('Error: $errorMessage');
},
onDownloadComplete: (TestResult data) {
print('Download complete: ${data.speed} Mbps');
},
onUploadComplete: (TestResult data) {
print('Upload complete: ${data.speed} Mbps');
},
onCancel: () {
print('Test cancelled');
},
);
}
高级用法
您可以自定义测试服务器URL和文件大小:
import 'package:flutter_speed_test_plus/flutter_speed_test_plus.dart';
void startCustomSpeedTest() {
final speedTest = FlutterInternetSpeedTest();
speedTest.startTesting(
useFastApi: false, // 使用自定义服务器,而不是Fast.com
downloadTestServer: 'https://your-download-server.com/testfile', // 自定义下载服务器URL
uploadTestServer: 'https://your-upload-server.com/upload', // 自定义上传服务器URL
fileSize: 20, // 测试文件大小,默认为10MB
onStarted: () {
print('Speed test started');
},
onCompleted: (TestResult download, TestResult upload) {
print('Download Speed: ${download.speed} Mbps');
print('Upload Speed: ${upload.speed} Mbps');
},
onProgress: (double percent, TestResult data) {
print('Progress: $percent%');
},
onError: (String errorMessage, String speedTestError) {
print('Error: $errorMessage');
},
onDownloadComplete: (TestResult data) {
print('Download complete: ${data.speed} Mbps');
},
onUploadComplete: (TestResult data) {
print('Upload complete: ${data.speed} Mbps');
},
onCancel: () {
print('Test cancelled');
},
);
}
配置选项
-
默认服务器URL:
- 下载服务器:
https://fast.com/
- 上传服务器:
https://fast.com/
- 下载服务器:
-
自定义选项:
- 服务器URL:指定自己的
downloadTestServer
和uploadTestServer
。 - 文件大小:设置
fileSize
参数(以MB为单位),默认为10MB。
- 服务器URL:指定自己的
回调描述
以下是所有可用的回调函数及其作用:
onStarted
:当速度测试开始时调用。onCompleted
:当测试完成时调用,返回最终的下载和上传速度。onProgress
:当测试进度更新时调用,返回进度百分比和中间结果。onError
:当测试过程中发生错误时调用。onDefaultServerSelectionInProgress
:当使用Fast.com API时,服务器选择过程中调用。onDefaultServerSelectionDone
:当使用Fast.com API时,服务器选择完成后调用。onDownloadComplete
:当下载测试完成时调用。onUploadComplete
:当上传测试完成时调用。onCancel
:当测试被取消时调用。
支持的平台
- iOS
- Android
完整示例
以下是一个完整的示例,展示了如何在Flutter应用中使用 flutter_speed_test_plus
插件进行网络速度测试,并显示测试结果和进度。
import 'package:flutter/material.dart';
import 'package:flutter_speed_test_plus/flutter_speed_test_plus.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/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](/user/override)
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
reset();
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF1A237E), Color(0xFF283593), Color(0xFF3949AB)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
),
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"Internet Speed Test",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildInfoCard(
title: "IP Address",
value: _ip ?? '--',
icon: Icons.public,
color: Colors.blueAccent,
),
_buildInfoCard(
title: "ASN",
value: _asn ?? '--',
icon: Icons.network_check,
color: Colors.orangeAccent,
),
_buildInfoCard(
title: "ISP",
value: _isp ?? '--',
icon: Icons.wifi,
color: Colors.tealAccent,
),
],
),
const SizedBox(height: 30),
if (_isServerSelectionInProgress)
const Text(
"Selecting Server...",
style: TextStyle(color: Colors.white70),
)
else
Column(
children: [
_buildProgressCard(
title: "Download Speed",
progress: _downloadProgress,
rate: _downloadRate,
unit: _unitText,
time: _downloadCompletionTime,
color: Colors.greenAccent,
),
const SizedBox(height: 20),
_buildProgressCard(
title: "Upload Speed",
progress: _uploadProgress,
rate: _uploadRate,
unit: _unitText,
time: _uploadCompletionTime,
color: Colors.amberAccent,
),
],
),
const SizedBox(height: 20),
if (!_testInProgress)
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 15, horizontal: 40),
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)),
),
onPressed: () async {
reset();
await startTest();
},
child: const Text(
"Start Testing",
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
)
else
Column(
children: [
const CircularProgressIndicator(),
const SizedBox(height: 10),
TextButton.icon(
onPressed: () {
internetSpeedTest.cancelTest();
reset();
},
icon: const Icon(Icons.cancel, color: Colors.red),
label: const Text(
"Cancel",
style: TextStyle(color: Colors.red),
),
),
],
),
],
),
),
),
),
),
);
}
Widget _buildProgressCard({
required String title,
required String progress,
required double rate,
required String unit,
required int time,
required Color color,
}) {
return Card(
color: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
shadowColor: Colors.black.withOpacity(0.3),
elevation: 10,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Text(
title,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: color,
),
),
const SizedBox(height: 10),
CircularProgressIndicator(
value: double.parse(progress) / 100,
color: color,
backgroundColor: Colors.grey.withOpacity(0.3),
),
const SizedBox(height: 10),
Text(
"$rate $unit",
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
if (time > 0)
Text(
"Time: ${(time / 1000).toStringAsFixed(2)} sec(s)",
style: const TextStyle(color: Colors.grey),
),
],
),
),
);
}
Widget _buildInfoCard({
required String title,
required String value,
required IconData icon,
required Color color,
}) {
return Card(
color: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
elevation: 6,
shadowColor: Colors.black.withOpacity(0.3),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
children: [
Icon(icon, color: color, size: 30),
const SizedBox(height: 5),
Text(
title,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: color,
),
),
const SizedBox(height: 5),
Text(
value,
style: const TextStyle(
fontSize: 14,
color: Colors.black87,
),
),
],
),
),
);
}
Future<void> startTest() async {
await internetSpeedTest.startTesting(
onStarted: () {
setState(() => _testInProgress = true);
},
onCompleted: (download, upload) {
setState(() {
_downloadRate = download.transferRate;
_downloadCompletionTime = download.durationInMillis;
_uploadRate = upload.transferRate;
_uploadCompletionTime = upload.durationInMillis;
_testInProgress = false;
});
},
onProgress: (percent, data) {
setState(() {
if (data.type == TestType.download) {
_downloadRate = data.transferRate;
_downloadProgress = percent.toStringAsFixed(2);
} else {
_uploadRate = data.transferRate;
_uploadProgress = percent.toStringAsFixed(2);
}
});
},
onDefaultServerSelectionInProgress: () {
setState(() => _isServerSelectionInProgress = true);
},
onDefaultServerSelectionDone: (client) {
setState(() {
_isServerSelectionInProgress = false;
_ip = client?.ip;
_asn = client?.asn;
_isp = client?.isp;
});
},
onError: (errorMessage, speedTestError) {
reset();
},
onCancel: () {
reset();
},
);
}
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;
});
}
}
更多关于Flutter网络速度测试插件flutter_speed_test_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter网络速度测试插件flutter_speed_test_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用flutter_speed_test_plus
插件来进行网络速度测试的示例代码。这个插件允许你测试下载和上传速度,以及延迟(ping)。
首先,确保你已经在pubspec.yaml
文件中添加了flutter_speed_test_plus
依赖:
dependencies:
flutter:
sdk: flutter
flutter_speed_test_plus: ^x.y.z # 请将 x.y.z 替换为当前最新版本号
然后运行flutter pub get
来获取依赖。
接下来,在你的Flutter应用中,你可以使用以下代码来执行网络速度测试:
import 'package:flutter/material.dart';
import 'package:flutter_speed_test_plus/flutter_speed_test_plus.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
SpeedTest? speedTest;
String result = '';
@override
void initState() {
super.initState();
performSpeedTest();
}
Future<void> performSpeedTest() async {
try {
speedTest = SpeedTest(urls: [
'https://speedtest.tele2.net/1MB.zip', // 下载测试文件URL
// 可以添加更多URL进行多线程下载测试
]);
SpeedTestResult result = await speedTest!.testConnection();
setState(() {
this.result = 'Download Speed: ${result.downloadMbps.toStringAsFixed(2)} Mbps\n'
'Upload Speed: ${result.uploadMbps.toStringAsFixed(2)} Mbps\n'
'Ping: ${result.ping.toStringAsFixed(2)} ms';
});
} catch (e) {
setState(() {
this.result = 'Error: ${e.toString()}';
});
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Network Speed Test'),
),
body: Center(
child: Text(result),
),
),
);
}
}
在这个示例中,我们创建了一个简单的Flutter应用,它在启动时执行网络速度测试。我们使用SpeedTest
类并传递一个包含下载测试文件URL的列表。然后,我们调用testConnection()
方法来执行测试,并在结果返回后更新UI。
注意:
- URL选择:你需要选择一个合适的下载测试文件URL。这个URL应该是一个足够大的文件,以便能够准确测量下载速度。
- 多线程测试:你可以通过传递多个URL来启用多线程下载测试,这样可以更准确地模拟实际使用情况下的下载速度。
- 错误处理:在实际应用中,你应该添加更多的错误处理逻辑来处理各种可能的异常情况,例如网络不可用、测试文件无法访问等。
这个示例提供了一个基本的框架,你可以根据需要进行扩展和修改。