Kaya Ryuuna
Kaya Ryuuna

Reputation: 764

Flutter - list duplicates old and new values

I have a method for receiving push from Firebase Cloud Messaging, and within it, the notification is allocated within a list. What happens is that this method is making the old value a duplicate of the new value.

The first push i have send

The second push, transforms the first, and the two are the same

Firebase method:

FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
  if (message.notification != null) {

      widget._localNotificationList.title = message.notification.title;
      widget._localNotificationList.body = message.notification.body;

      widget._pushDecode.notifList.add(widget._localNotificationList);
      
      savePush(); //this method maintains notification on the user's screen, with sharedPreferences 
    setState(() {});
  }
});

Page View:

ListView.builder(
              itemCount: widget._pushDecode.notifList.length,
              itemBuilder: (context, i) {
                return Card(
                  margin: EdgeInsets.all(10),
                  elevation: 4,
                  child: ListTile(
                    trailing: IconButton(
                      icon: Icon(Icons.delete),
                      onPressed: () => removePush(i),
                    ),
                    title: Text(
                      widget._pushDecode.notifList.reversed.elementAt(i).title,
                    ),
                    subtitle: Text(
                      widget._pushDecode.notifList.reversed.elementAt(i).body,
                    ),
                  ),
                );
              },
            ),

Upvotes: 0

Views: 294

Answers (1)

Ayad
Ayad

Reputation: 691

You need to use the key value because it does not know if the widget that was in the position you are adding it for example is different then the previous, but using keys he can always know that two widgets are different when they are the same type like your card.

ListView.builder(
              itemCount: widget._pushDecode.notifList.length,
              itemBuilder: (context, i) {
                return Card(
                  key: UniqueKey(), // you can also use ValueKey('this must be unique for each element in the list.')
                  margin: EdgeInsets.all(10),
                  elevation: 4,
                  child: ListTile(
                    trailing: IconButton(
                      icon: Icon(Icons.delete),
                      onPressed: () => removePush(i),
                    ),
                    title: Text(
                      widget._pushDecode.notifList.reversed.elementAt(i).title,
                    ),
                    subtitle: Text(
                      widget._pushDecode.notifList.reversed.elementAt(i).body,
                    ),
                  ),
                );
              },
            ),

Upvotes: 2

Related Questions