У меня есть простое приложение для трепетания, я хочу сканировать устройства и подключиться к ним, проблема в том, что сканирующие организации всегда пустые, ниже мой код для контроллера и представления < /p>
Controller < /p>
import 'dart:async';
import 'dart:io';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
class BleConnexionController extends GetxController {
//TODO: Implement BleConnexionController
late BluetoothDevice connectedDevice;
Stream get scanResults => FlutterBluePlus.scanResults;
@override
void onInit() {
super.onInit();
initializeBluetooth();
}
@override
void onReady() {
super.onReady();
}
@override
void onClose() {
super.onClose();
}
Future initializeBluetooth() async {
// Request Bluetooth permissions
final status = await Permission.bluetooth.status;
print('the status $status');
if (status.isGranted) {
// Bluetooth permission is granted, now turn on Bluetooth
// Check if Bluetooth is available on the device
if (await FlutterBluePlus.isAvailable) {
// Check if Bluetooth is already on
final state = await FlutterBluePlus.adapterState.first;
if (state == BluetoothAdapterState.off) {
if (Platform.isAndroid) {
try{
await FlutterBluePlus.turnOn();
}catch(e){
print(e);
}
}
}
// You can now use FlutterBlue to work with Bluetooth devices
// Example: List devices = await flutterBlue.connectedDevices;
} else {
// Bluetooth is not available on this device
print('Bluetooth is not available on this device.');
}
} else {
// Permission not granted
print('Bluetooth permission not granted.');
}
}
var subscription = FlutterBluePlus.scanResults.listen(
(results) {
for (ScanResult r in results) {
print('${r.device.remoteId}: "${r.device.localName}" found! rssi: ${r.rssi}');
}
},
onError: (e) => print(e)
);
Future scan() async {
List devices = await FlutterBluePlus.connectedSystemDevices;
// Start scanning
await FlutterBluePlus.startScan(timeout: const Duration(milliseconds: 100), androidUsesFineLocation: false); // Stop scanning
await FlutterBluePlus.stopScan();
}
}
< /code>
Функция сканирования вызывается в представлении при нажатии кнопки сканирования < /p>
View < /p>
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import '../controllers/ble_connexion_controller.dart';
class BleConnexionView extends GetView {
const BleConnexionView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BleConnexionView'),
centerTitle: true,
),
body: GetBuilder(
init: BleConnexionController(),
builder: (controller) {
return SingleChildScrollView(
child: Column(children: [
const SizedBox(height: 20,),
Center(
child: ElevatedButton(onPressed: () => controller.scan(),
child: Text("Scan"),),
),
StreamBuilder(
stream: controller.scanResults,
builder: (context,snapshot){
if (snapshot.data != null && snapshot.data!.isNotEmpty){
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (context,index){
final data = snapshot.data![index];
return Card(
elevation: 2,
child: ListTile(
title: Text(data.device.localName),
subtitle: Text(data.device.id.id),
trailing: ElevatedButton(
onPressed: () async {
controller.connectedDevice=data.device;
//controller.connectDevice().then((value) => Get.off(const HomePage()));
},
child: Text("Connect"),
),
),
);
},
);
}else{
return const Center(child: Text("No devices found"),);
}
})
]),
);
},),
);}
}
< /code>
Я пробовал много версий трепетания (3.13.3
3.13.2
3.10.6 (Active)
3.10.0
)
Строитель ScanResult>
Подробнее здесь: https://stackoverflow.com/questions/771 ... r-scanning
Flutter_blue_plus не показывает устройства после сканирования ⇐ Android
Форум для тех, кто программирует под Android
-
Anonymous
1750571900
Anonymous
У меня есть простое приложение для трепетания, я хочу сканировать устройства и подключиться к ним, проблема в том, что сканирующие организации всегда пустые, ниже мой код для контроллера и представления < /p>
Controller < /p>
import 'dart:async';
import 'dart:io';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
class BleConnexionController extends GetxController {
//TODO: Implement BleConnexionController
late BluetoothDevice connectedDevice;
Stream get scanResults => FlutterBluePlus.scanResults;
@override
void onInit() {
super.onInit();
initializeBluetooth();
}
@override
void onReady() {
super.onReady();
}
@override
void onClose() {
super.onClose();
}
Future initializeBluetooth() async {
// Request Bluetooth permissions
final status = await Permission.bluetooth.status;
print('the status $status');
if (status.isGranted) {
// Bluetooth permission is granted, now turn on Bluetooth
// Check if Bluetooth is available on the device
if (await FlutterBluePlus.isAvailable) {
// Check if Bluetooth is already on
final state = await FlutterBluePlus.adapterState.first;
if (state == BluetoothAdapterState.off) {
if (Platform.isAndroid) {
try{
await FlutterBluePlus.turnOn();
}catch(e){
print(e);
}
}
}
// You can now use FlutterBlue to work with Bluetooth devices
// Example: List devices = await flutterBlue.connectedDevices;
} else {
// Bluetooth is not available on this device
print('Bluetooth is not available on this device.');
}
} else {
// Permission not granted
print('Bluetooth permission not granted.');
}
}
var subscription = FlutterBluePlus.scanResults.listen(
(results) {
for (ScanResult r in results) {
print('${r.device.remoteId}: "${r.device.localName}" found! rssi: ${r.rssi}');
}
},
onError: (e) => print(e)
);
Future scan() async {
List devices = await FlutterBluePlus.connectedSystemDevices;
// Start scanning
await FlutterBluePlus.startScan(timeout: const Duration(milliseconds: 100), androidUsesFineLocation: false); // Stop scanning
await FlutterBluePlus.stopScan();
}
}
< /code>
Функция сканирования вызывается в представлении при нажатии кнопки сканирования < /p>
View < /p>
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import '../controllers/ble_connexion_controller.dart';
class BleConnexionView extends GetView {
const BleConnexionView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BleConnexionView'),
centerTitle: true,
),
body: GetBuilder(
init: BleConnexionController(),
builder: (controller) {
return SingleChildScrollView(
child: Column(children: [
const SizedBox(height: 20,),
Center(
child: ElevatedButton(onPressed: () => controller.scan(),
child: Text("Scan"),),
),
StreamBuilder(
stream: controller.scanResults,
builder: (context,snapshot){
if (snapshot.data != null && snapshot.data!.isNotEmpty){
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (context,index){
final data = snapshot.data![index];
return Card(
elevation: 2,
child: ListTile(
title: Text(data.device.localName),
subtitle: Text(data.device.id.id),
trailing: ElevatedButton(
onPressed: () async {
controller.connectedDevice=data.device;
//controller.connectDevice().then((value) => Get.off(const HomePage()));
},
child: Text("Connect"),
),
),
);
},
);
}else{
return const Center(child: Text("No devices found"),);
}
})
]),
);
},),
);}
}
< /code>
Я пробовал много версий трепетания (3.13.3
3.13.2
3.10.6 (Active)
3.10.0
)
Строитель ScanResult>
Подробнее здесь: [url]https://stackoverflow.com/questions/77138174/flutter-blue-plus-is-not-showing-devices-after-scanning[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия