我有一个存储两种类型对象的数组,这两种类型是OwnMessageCard
和ReplyCard
。
late IO.Socket _socket;
var myMessagesList = < Widget > [];
_connectSocket() async {
final prefs = await SharedPreferences.getInstance();
myUsername = prefs.getString('myUsername') !;
_socket.onConnect((data) => print('Connection established'));
_socket.onConnectError((data) => print('Connection error: $data'));
_socket.onDisconnect((data) => print('Socket disconnected.'));
_socket.on(myUsername, (data) {
setState(() {
myMessagesList.add(ReplyCard(
senderMessage: data['message'].toString(),
sentAt: data['sentAt'].toString(),
));
});
_socket.emit('seen', {
'sender': myUsername,
'target': targetUsername
});
});
_socket.on("$myUsername/seen", (data) {
setState(() {
myMessagesList.forEach((element) {
if (element == OwnMessageCard) {
//Some codes here to change 'isSeen' property to 'true'
}
});
});
});
}
当消息来自_socket.on("$myUsername/seen", (data){}
时,我想将所有OwnMessageCard
对象的isSeen
属性设置为true
。OwnMessageCard
有myMessage
和isSeen
两个属性。如何做到这一点?
更新:OwnMessageCard
类别:
class OwnMessageCard extends StatelessWidget {
OwnMessageCard({super.key, required this.myMessage, required this.isSeen});
final String myMessage;
bool isSeen;
@override
Widget build(BuildContext context) {
final currentTime = DateTime.now();
return Align(
alignment: Alignment.centerRight,
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width - 45, minWidth: 180),
child: Card(
elevation: 1,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
color: ownMessageBackColor,
margin: const EdgeInsets.symmetric(horizontal: 15, vertical: 5),
child: Stack(
children: [
Padding(
padding: const EdgeInsets.only(
left: 25, right: 10, top: 5, bottom: 25),
child: Text(
myMessage,
style: const TextStyle(fontSize: 18, fontFamily: 'FMitra'),
),
),
Positioned(
bottom: 4,
right: 10,
child: Row(
children: [
Icon(
Icons.done_all,
size: 20,
color: isSeen ? Colors.blue : Colors.grey,
),
const SizedBox(
width: 5,
),
Text(
"${currentTime.hour}:${currentTime.minute} | ${currentTime.year}-${currentTime.month}-${currentTime.day}",
style: TextStyle(fontSize: 12, color: Colors.grey),
)
],
),
)
],
),
),
),
);
}
}
1条答案
按热度按时间uxhixvfz1#
首先,你不能用
==
来比较变量和类型,你需要使用is
,其次,你可以像这样修改你的数据,我假设这是你的类模型:您可以像这样更改数据: