在Flutter中更改数组中所有对象的属性

watbbzwu  于 2022-12-05  发布在  Flutter
关注(0)|答案(1)|浏览(415)

我有一个存储两种类型对象的数组,这两种类型是OwnMessageCardReplyCard

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属性设置为trueOwnMessageCardmyMessageisSeen两个属性。如何做到这一点?

更新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),
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
uxhixvfz

uxhixvfz1#

首先,你不能用==来比较变量和类型,你需要使用is,其次,你可以像这样修改你的数据,我假设这是你的类模型:

class OwnMessageCard {
  final bool isSeen;
  final String message;

  OwnMessageCard({
    required this.isSeen,
    required this.message,
  });
}

您可以像这样更改数据:

_socket.on("$myUsername/seen", (data) {
        var newList = myMessagesList.map((e) => e is OwnMessageCard ? OwnMessageCard(isSeen: true,message: e.message ) : e)
            .toList();

        setState(() {
            myMessagesList = newList;
        });
    });

相关问题