Flutter-发现局域网中的设备

news/2024/10/16 10:09:09 标签: 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]),
                  );
                },
              ),
            ),
        ],
      ),
    );
  }
}


http://www.niftyadmin.cn/n/5707706.html

相关文章

新生编程入门的方式探讨

关于如何编程入门&#xff0c;这是一个很好的问题。在上大学之前&#xff0c;并没有怎么接触电脑的我&#xff0c;也许可以谈一谈。 还记得在高中的时候&#xff0c;因为很多同学去网吧玩电脑打游戏&#xff0c;被学校开除&#xff0c;老师谆谆教诲大家不要去网吧&#xff0c;所…

Java @RequestPart注解:同时实现文件上传与JSON对象传参

RequestPart注解&#xff1a;用于处理multipart/form-data请求的一部分&#xff0c;通常用于文件上传或者处理表单中的字段。 java后端举例&#xff1a; PostMapping("/fileTest")public AjaxResult fileTest(RequestPart("file") MultipartFile file,Req…

nginx与apache相比

文章目录 架构并发处理能力静态内容处理动态内容处理配置复杂度稳定性 架构 Nginx&#xff1a;采用异步非阻塞的事件驱动架构&#xff0c;能够高效地处理大量并发连接。Apache&#xff1a;采用多进程模型&#xff0c;每个请求都会创建一个独立的进程&#xff0c;对于并发连接的…

博客|基于springBoot的精简博客系统设计与实现(附项目源码+论文+数据库)

私信或留言即免费送开题报告和任务书&#xff08;可指定任意题目&#xff09; 目录 一、摘要 二、相关技术 三、系统设计 &#xff08;1&#xff09;个人中心 &#xff08;2&#xff09;管理员管理 &#xff08;3&#xff09;用户管理 &#xff08;4&#xff09;博客信…

c# 中List的介绍说明

一.List的定义说明 在C#中&#xff0c;List<T>是一个泛型类&#xff0c;它允许你创建一个元素类型为T的强类型列表。List<T>类位于System.Collections.Generic命名空间下&#xff0c;是.NET Framework的一部分。 二.List<T>的一些常用操作和方法 2.1添加元…

地级市-知识产权保护水平测算(2003-2021年)

知识产权保护水平是指权利人的知识产权依法受到保护的程度或强度。它通常由国家赋权&#xff0c;使创造者在一定时期内享有智力成果的专有独占权。知识产权保护具有时间性、专有性和区域性三大特征。 2003年-2021年地级市-知识产权保护水平测算&#xff08;数据整理&#xff0…

PHP 函数 func_num_args() 的作用

func_num_args() 是 PHP 中的一个内置函数&#xff0c;用于获取传递给当前用户定义函数的参数个数。这个函数特别有用于处理可变数量的参数&#xff08;也称为可变参数列表&#xff09;。 语法 int func_num_args ( void ) 返回值 func_num_args() 返回一个整数&#xff0c…

ajax地址参数与data参数运用

ajax的运用 因为项目在进行安全准入检查&#xff0c;也是代码安全的一种处理方式吧&#xff0c;然后我们在进行行加密以及模块加密&#xff0c;就是因为行信息中存在行id可以通过更换行id进行查询其他行的信息&#xff0c;模块也是一样&#xff0c;可能会出现垂直越权以及水平…