본문 바로가기

[Flutter] Flutter blue Plus 1.30.7 버전 기준 연결 예제

I'm 영서 2023. 12. 26.
반응형

 

안드로이드 권한 업데이트로 인해 블루투스가 잘 안되서 보니 업데이트 많이했음. 따라서 최신 버전에 맞추어 예제를 작성함. (이걸 쓰는 도중에도 1.30.8에서 1.31.3 으로 올랏다;)

 

내가 사용한 버전은 1.30.8 버전을 사용했다.

 

flutter pub add flutter_blue_plus

 

를 통해 flutter blue plus를 추가해줬다.

 

특정 StatefulScreen이 생성될 때 

생성한 블루투스 셋팅 매서드를 호출하고 적당히 listen을 해 주었다. listen 하여 나온 리스트를 반복하여 특정 platform 이름을 가진 기기와 연동하였다. 여기서 중요한 문법은 then을 통해 연결된 이후에 추가적인 작업을 진행해 주어야만 한다는것.. 

 

추가로 블루투스의 맥 주소로 연결하도록 변경예정 + 데이터베이스에 해당 블루투스의 맥주소를 저장하여 유저가 보유한 블루투스 기기만 접속되도록 수정할 예정.

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    flutterBlueSettings();
    selectedBluetoothItem.addListener(() {
      setState(() {});
    });

    flutterBlueInit();

    // flutterBluePlusInit();
  }

  void flutterBlueSettings() async {
    // first, check if bluetooth is supported by your hardware
    if (await FlutterBluePlus.isSupported == false) {
      print("Bluetooth not supported by this device");
      return;
    }

    // handle bluetooth on & off
    FlutterBluePlus.adapterState.listen(
      (BluetoothAdapterState state) {
        print(state);
        if (state == BluetoothAdapterState.on) {
          // usually start scanning, connecting, etc
        } else {
          // show an error to the user, etc
        }
      },
    );

    // turn on bluetooth ourself if we can
    if (Platform.isAndroid) {
      await FlutterBluePlus.turnOn();
    }
  }
  

  void flutterBlueInit() async {
    onStartScan();

    print('try connection');
    // listen to scan results
    FlutterBluePlus.scanResults.listen((results) async {
      if (results.isNotEmpty) {
        ScanResult r = results.last; // the most recently found device
        if (r.device.platformName == "WaterPump Ctlr") {
          FlutterBluePlus.connectedDevices.add(r.device);
          await r.device.connect().then((value) {
            labelText = 'Qua에  연결되었습니다!';

            selectedBluetoothItem.addItem(r.device);
          });

          onStopScan();
          setState(() {});
        }
      }
    }, onError: (e) => print(e));

    await FlutterBluePlus.adapterState
        .where((val) => val == BluetoothAdapterState.on)
        .first;
  }

  Future onStartScan() async {
    int divisor = Platform.isAndroid ? 8 : 1;
    await FlutterBluePlus.startScan(
        timeout: const Duration(seconds: 7),
        continuousUpdates: true,
        continuousDivisor: divisor);
    setState(() {});
  }

  Future onStopScan() async {
    FlutterBluePlus.stopScan();
  }

 

반응형

댓글