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]),
                  );
                },
              ),
            ),
        ],
      ),
    );
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值