自学内容网 自学内容网

Flutter-发现局域网中的设备

前言

现在有一个需求:要能够获取到局域网中的遮阳帘设备。通过搜索发现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<MyApp1> createState() => _MyApp1State();
}

class _MyApp1State extends State<MyApp1> {
  List<String> devices = [];
  bool isScanning = false;
  List<String> messageLog = <String>[];

//设备扫描函数
  Future<void> 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]),
                  );
                },
              ),
            ),
        ],
      ),
    );
  }
}


原文地址:https://blog.csdn.net/nonagontech/article/details/142832319

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!