前言
现在有一个需求:要能够获取到局域网中的遮阳帘设备。通过搜索发现flutter_mdns_plugin可以满足这个需求
Pub:flutter_mdns_plugin | Flutter package
GitHub:https://github.com/terrabythia/flutter_mdns_plugin
MDNS服务类型
要根据不同的MDNS服务类型来发现对应的设备
服务类型参考:mDNS的服务类型
全部代码
import 'package:flutter/material.dart';
import 'package:flutter_mdns_plugin/flutter_mdns_plugin.dart';
class MyApp1 extends StatefulWidget {
const MyApp1({super.key});
@override
State createState() => _MyApp1State();
}
class _MyApp1State extends State {
List devices = [];
bool isScanning = false;
List messageLog = [];
//设备扫描函数
Future scanDevices() async {
setState(() {
isScanning = true;
devices.clear();
});
const String serviceType = '_http._tcp';
DiscoveryCallbacks discoveryCallbacks = DiscoveryCallbacks(
onDiscovered: (ServiceInfo info) {
print("Discovered ${info.toString()}");
},
onDiscoveryStarted: () {
print("Discovery started");
},
onDiscoveryStopped: () {
print("Discovery stopped");
},
onResolved: (ServiceInfo info) {
print("Resolved Service ${info.toString()}");
setState(() {
devices.add(info.toString());
});
},
);
final mdnsPlugin = FlutterMdnsPlugin(discoveryCallbacks: discoveryCallbacks);
try {
await mdnsPlugin.startDiscovery(serviceType);
await Future.delayed(const Duration(seconds: 1)); // 扫描5秒钟
await mdnsPlugin.stopDiscovery();
} catch (e) {
print('Error during device scan: $e');
}
setState(() {
isScanning = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Device Scanner'),
),
body: Column(
children: [
ElevatedButton(
onPressed: isScanning ? null : scanDevices,
child: const Text('Scan Devices'),
),
const SizedBox(height: 16),
if (isScanning)
const CircularProgressIndicator()
else if (devices.isEmpty)
Text('No devices found.')
else
Expanded(
child: ListView.builder(
itemCount: devices.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(devices[index]),
);
},
),
),
],
),
);
}
}