You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何在指定蓝牙设备相关代码中添加条件判断?

两段Flutter代码添加名称判断的实现方案

代码1(构造函数初始化逻辑修改)

原代码是Dart构造函数的初始化列表,要添加p.name == "xx"的条件判断,可根据需求选择两种实现方式:

方式1:直接修改字段值

如果只是针对name字段做条件替换,用三元运算符在初始化列表中处理:

BluetoothDevice.fromProto(protos.BluetoothDevice p)
    : id = DeviceIdentifier(p.remoteId),
      name = p.name == "xx" ? "自定义名称" : p.name, // 名称为"xx"时替换为自定义值
      type = BluetoothDeviceType.values[p.type.value];

方式2:复杂逻辑处理

如果需要过滤设备、抛出异常这类复杂操作,改用工厂构造函数:

factory BluetoothDevice.fromProto(protos.BluetoothDevice p) {
  if (p.name == "xx") {
    // 示例:拒绝创建该设备并抛出异常
    throw ArgumentError("禁止初始化名称为'xx'的蓝牙设备");
    // 也可返回自定义实例:
    // return BluetoothDevice._(DeviceIdentifier(p.remoteId), "替换名称", BluetoothDeviceType.values[p.type.value]);
  }
  return BluetoothDevice._(DeviceIdentifier(p.remoteId), p.name, BluetoothDeviceType.values[p.type.value]);
}

// 私有构造函数供工厂方法调用
BluetoothDevice._(this.id, this.name, this.type);

代码2(Builder模式下的条件处理)

原代码是将BluetoothDevice转为Proto对象,在设置name的逻辑中嵌套条件判断即可:

static Protos.BluetoothDevice from(BluetoothDevice device) {
  Protos.BluetoothDevice.Builder p = Protos.BluetoothDevice.newBuilder();
  p.setRemoteId(device.getAddress());
  String name = device.getName();
  
  if (name != null) {
    if (name == "xx") {
      // 示例1:替换为指定名称
      p.setName("替换后的名称");
      // 示例2:跳过设置名称(清空字段)
      // p.clearName();
    } else {
      p.setName(name);
    }
  }
  
  return p.build(); // 补充原代码缺失的build方法调用
}

内容的提问来源于stack exchange,提问作者rania

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 01:20:33