I have a regular Firestore Stream builder here:

    child: StreamBuilder(
              stream: FirebaseFirestore.instance
                  .collection('test')
                  .orderBy('descending')
                  .snapshots(),
              builder: (context, snapshot) {

                return ListView.builder(
                  itemCount: snapshot.data.docs.length,
                  itemBuilder: (context, index) {
                    DocumentSnapshot ds = snapshot.data.docs[index];
                    return Padding(
                      child: ListTile(
                         onTap: () {},
                          trailing: Container(
                            child: IconButton(
                              icon: Icon(
                                Icons.check,
                                color: Colors.black,
                                size: 30,
                              ),
                              onPressed: () {},

                          title: Text(
                            'ds['test'],

                        )

I would want to put this function in it, so that after each item in stream builder is added (in real time), that function to fire off, it is the audio sound function from the audioplayers Dart library:

playSound(){
 final sound = AudioCache();
 sound.play('mysound.mp3');

Any ideas how this would work?


Solution 1: dvijai

You need to check length of existing data first. if it is not the same then play a sound else no action.

final sound = AudioCache();
   int dataLength = 0;
  Stream<List<MESSAGELIST>> chatStream() async* {
    while (true) {
      await Future.delayed(Duration(milliseconds: 500));
      List<MESSAGELIST> someChat = await getMessageList(bid);
      if(someChat.length > dataLength) {  setState(() {
        sound.play('ding.mp3');
        createChatNotifications();
        dataLength = someChat.length;
      });}
      yield someChat;
    }
  }