How to sort Bluetooth devices using RSSI in Flutter

Viewed 573

I have a flutter project where I'm using a library named flutter_blue. When I scan for bluetooth devices I'm getting a list of devices and also the signal strength measured in decibels (RSSI). The question is how can I sort that list of devices by RSSI property which I have it for each device found ?

Here is a link to my source code:

Scan Bluetooth Devices Demo

Here is my block of code where I think I should do the sort by r.rssi but I can't manage to do it.

      StreamBuilder<List<ScanResult>>(
                stream: FlutterBlue.instance.scanResults,
                initialData: [],
                builder: (c, snapshot) => Column(
                  children: snapshot.data
                      .map(
                        (r) => ScanResultTile(
                          result: r,
                          onTap: () => Navigator.of(context)
                              .push(MaterialPageRoute(builder: (context) {
                            r.device.connect();
                            return DeviceScreen(device: r.device);
                          })),
                        ),
                      )
                      .toList(),
                ),
              ),

Thanks for reading this.

1 Answers

You need to add sort() function at the end of tolist() and write logic according to ascending or descending order

Here is example:

                stream: FlutterBlue.instance.scanResults,
                initialData: [],
                builder: (c, snapshot) => Column(
                  children: snapshot.data
                      .map(
                        (r) => ScanResultTile(
                          result: r,
                          onTap: () => Navigator.of(context)
                              .push(MaterialPageRoute(builder: (context) {
                            r.device.connect();
                            return DeviceScreen(device: r.device);
                          })),
                        ),
                      )
                     .toList()..sort((a,b)=>b.result.rssi.compareTo(a.result.rssi)),
                ),
              ),
Related