【问题标题】:How to update specific widget after got response from listening socket.on?从监听 socket.on 获得响应后如何更新特定小部件?
【发布时间】:2019-10-06 11:57:20
【问题描述】:

我有 2 个单独的类,Socketio 类和 HomePage 类。 我想在 Socketio 类中的 socket.on 得到响应后更新 HomePage, 如何从 Socketio 类更新 HomePage 中的小部件?

我尝试使用提供程序库,但没有如何使用可监听提供程序

socket.on('chat message', (data) => {
    print("got reply chat"),
    setState(()) {}; // THIS setState not working because I try to separate socket class with UI widget
});

那么如何从一个类中触发 setState 特定的小部件/页面呢?

【问题讨论】:

标签: flutter socket.io flutter-provider


【解决方案1】:
        children: <Widget> [
          (Provider.of<Chat>(context).sender == "blank")
              ? Container()
              : model.detectNewChat(widget.roomId, Provider.of<Chat>(context)),
          Expanded(child: ListView(
            children: model.chats
                .map((chat) => ChatItem(chat, Provider.of<User>(context).id)).toList(),
          ),),
          new Divider(height: 1.0),

我通过使用 Provider.of(context) 解决了这个问题。 这是我的socket.io中的代码

  StreamController<Chat> chatController = StreamController<Chat>();

    socket.on('chat message', (data) => {

        print("got reply chat"),
        chatController.add(new Chat(data['roomId'], data['username'], "1123", data['message'], DateTime.now())),
    });

内部模型

  Widget detectNewChat(String currentRoomId, Chat newChat) {
    print(newChat.sender + " "+newChat.body);
    // TODO add filter if roomId not match with current room id
    if (currentRoomId == newChat.roomId) {
      addChat(newChat.roomId, newChat);
    }
    return Container();
  }

  addChat(String roomId, Chat chat) {
    setState(ViewState.Busy);

    _socketio.emitNewChat(roomId, chat.body);

    this.chats.add(chat);
    _isComposingMessage = false;
    _textEditingController.clear();

    setState(ViewState.Idle);
  }

所以如果有新的回复,我可以调用 chatController.add(newChat)。

因为 Provider 库中的 StreamProvider 将不断获取最后一个值。

【讨论】:

    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 2020-09-04
    • 2022-01-17
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 2015-06-05
    • 2014-03-23
    相关资源
    最近更新 更多