Reputation: 3
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.
Upvotes: 0
Views: 1243
Reputation: 353
Instead of keeping two separate lists for sent and received messages, why not just have one list of ChatMessageListItem for both? You can differentiate them using a property called type: sent or received, so you can determine to display on the left or right side of the ListView, different colors, etc. When a receivedMessage comes in, add it to the list. Now your ListView can handle both types of messages.
WebSocketChannel channel;
//final List<String> list = []; //Remove this line
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(() {
_messages.insert(0, new ChatMessageListItem(message: receivedMessage, type: MessageType.received));
//list.add(receivedMessage);
});
});
}
Upvotes: 1