How to make websocket response show in same widget as sent message like proper chat screen

297 views
Skip to first unread message

Michael Aworoghene

unread,
Jul 1, 2018, 2:00:11 PM7/1/18
to Flutter Dev
Hello, I am new to flutter and so far I'm currently in love with it.

I need a way to put the response from web-socket server on the left side; like a proper chat screen.

  WebSocketChannel channel;
final List<String> list = [];
final List<ChatMessageListItem> _messages = <ChatMessageListItem>[];
TextEditingController _textController;
bool _isComposing = false;

@override
void initState() {
super.initState();
channel = IOWebSocketChannel.connect('ws://echo.websocket.org');
_textController = TextEditingController();
channel.stream.listen((receivedMessage){
setState(() {
list.add(receivedMessage);
});
});
}

The code that displays the sent message

    void _handleSubmitted(String text) {
  setState(() {
_isComposing = false;
});
if (_textController.text.isNotEmpty) {
_textController.clear();

ChatMessageListItem message = new ChatMessageListItem(
sentMessage: text,
animationController: new AnimationController(
duration: new Duration(milliseconds: 350),
vsync: this,
),
);
setState(() {
_messages.insert(0, message);
});
message.animationController.forward();
channel.sink.add(message.sentMessage);
}
}


The Widget for showing sent Messages

    new Flexible(
  child: new ListView.builder(
padding: new EdgeInsets.all(8.0),
reverse: true,
itemBuilder: (_, int index) => _messages[index],
itemCount: _messages.length,
),
),


presently I am only able to show the received messages by using the below map

    new Flexible(
  child: Column(
children: list.map((receivedMessage) => Text(receivedMessage)).toList(),
),
),

Please, I need a way to make it display inside the ListView Builder.


Present result.



Didier Boelens

unread,
Jul 1, 2018, 4:53:31 PM7/1/18
to Flutter Dev
There is an article that details the notion of WebSockets, and in particular the way of handling response from the server.
I think it might be interesting in your case.
Here is the link to the article
Reply all
Reply to author
Forward
0 new messages