Listen to Stream and write only once to DB in Flutter Listen to Stream and write only once to DB in Flutter dart dart

Listen to Stream and write only once to DB in Flutter


Do you have a single subscription on stream or is it that the stream emits multiple same values? If it is the latter I suggest you try rxdart package. It is an implementation of ReactiveX for Dart. I am not that much experienced in reactive programming, but in my experience when I used BehaviorSubject from rxdart it didn't notify subscribers when the same value was added to it. So one thing you could do is to add each value from the QR Stream to BehaviorSubject, and instead subscribe (listen) to behavior subject for making queries to database.


I implemented a workaround for this. I assigned the value returned from stream which is scanData to the variable qrData and added to DB if qrData != scanData

void _onQRViewCreated(QRViewController controller) {    this.controller = controller;    controller.scannedDataStream.listen((scanData) async {      if (await canLaunch(scanData)) {        await launch(scanData);        if (qrData != scanData) {          setState(() {            qrData = scanData;          });          final data = QrModel(            content: scanData,            date: DateFormat.yMMMd().add_jm().format(DateTime.now()),          );          await dbProvider.addData(data);        }      } else {        if (!alertBoxOpen) {          if (qrData != scanData) {            setState(() {              qrData = scanData;            });            final data = QrModel(              content: scanData,              date: DateFormat.yMMMd().add_jm().format(DateTime.now()),            );            await dbProvider.addData(data);          }          setState(() => alertBoxOpen = true);          showDialog(              context: context,              builder: (context) {                return AlertDialog(                  content: Text(qrData),                  actions: [                    MaterialButton(                        child: Text('OK',                            style: TextStyle(                                fontSize: 18.0, fontWeight: FontWeight.bold)),                        onPressed: () {                          setState(() => alertBoxOpen = false);                          Navigator.of(context).pop();                        }),                  ],                );              });        }      }    });  }