Flutter - 列出重复的旧值和新值

Flutter - list duplicates old and new values

我有一个从 Firebase Cloud Messaging 接收推送的方法,在这个方法中,通知是在一个列表中分配的。发生的情况是此方法使旧值成为新值的副本。

Firebase 方法:

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(() {});
  }
});

页面浏览量:

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,
                    ),
                  ),
                );
              },
            ),

你需要使用键值,因为它不知道你添加它的位置的小部件是否与之前的不同,但是使用键他总是可以知道两个小部件是不同的它们与您的卡类型相同。

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,
                    ),
                  ),
                );
              },
            ),