Arpit Todewale
Arpit Todewale

Reputation: 129

Flutter Bluetooth low Energy. Unable to add scanned devices in the list

I am trying to create a list of all scanned devices and show in the ListTile.

this is my code

class HomePageState extends State<Home>{
 BluetoothDevice device;
 FlutterBlue flutterBlue = FlutterBlue.instance;
 List<AdvertiseData> dta = [];
 Future<List<AdvertiseData>> getAdvData() async{
 var beaconName;
 await flutterBlue.scan(timeout: Duration(seconds: 100)).listen((scanResult) {
  device = scanResult.device;
  beaconName = device.name;

  if(beaconName != ""){
    AdvertiseData d = AdvertiseData(beaconName, 1);
    dta.add(d);
    print(dta.length);
  }

 });
}

I am Getting the Data one by one and the list is getting updated everytime.

I/flutter (12631): 1      //list has 1 device
I/flutter (12631): .      //again list is initialized, contains 2 devices
I/flutter (12631): .
I/flutter (12631): .
I/flutter (12631): .
I/flutter (12631): .
I/flutter (12631): 142   //list is initialized,upto 142 devices

All i want is a single list(or the last list) so that i can show the data in the ListTile.

Upvotes: 0

Views: 3679

Answers (1)

Claudio Castro
Claudio Castro

Reputation: 1569

As long as you do not stop scanning with FlutterBlue.instance.stopScan () it will continue to update the list. This is normal behavior, just know how to deal with it.

import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Blue'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool scanning = false;
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  BluetoothDevice device;
  FlutterBlue flutterBlue = FlutterBlue.instance;
  List<ScanResult> dta = [];

  startStop() {
    if (scanning) {
      flutterBlue.stopScan();
      _scaffoldKey.currentState.showSnackBar(SnackBar(
        content: Text("you have ${dta.length} devices"),
      ));
    } else {
      flutterBlue.startScan(timeout: Duration(seconds: 4));
    }
    setState(() {
      scanning = !scanning;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text(widget.title),
        actions: <Widget>[
          FlatButton(
            child: Text(
              scanning ? "Stop Scanning" : "Start Scanning",
              style: TextStyle(color: Colors.white, fontSize: 14),
            ),
            onPressed: () {
              startStop();
            },
          )
        ],
      ),
      body: StreamBuilder<List<ScanResult>>(
        stream: FlutterBlue.instance.scanResults,
        initialData: [],
        builder: (c, snapshot) {
          dta = snapshot.data;
          return ListView.builder(
            itemCount: snapshot.data.length,
            itemBuilder: (context, index) {
              return Text(snapshot.data[index].device.name);
            },
          );
        },
      ),
    );
  }
}

Upvotes: 1

Related Questions