How can I use the websocket package with dart web? I have the following code
import 'package:projectname/data/chat/chat_message.dart';
import 'package:projectname/data/chat/chat_provider.dart';
import 'package:web_socket_channel/io.dart';
import '../path.dart';
class MockChatProvider implements ChatProvider {
@override
IOWebSocketChannel connect() {
return IOWebSocketChannel.connect(Uri.parse(Path.joinChat));
}
@override
sendChatMessage(IOWebSocketChannel channel, ChatMessage message) {
channel.sink.add(message.toJson());
}
}
But when I try to connect I get the following error
Unsupported operation: Platform._version
The package does say it supports web. What am I doing wrong?
CodePudding user response:
I think the issue is that you are importing package:web_socket_channel/io.dart
for web and you should instead import package:web_socket_channel/web_socket_channel.dart
.
Related GitHub issue on package's repo: https://github.com/dart-lang/web_socket_channel/issues/159
CodePudding user response:
Just use the package package:web_socket_channel/web_socket_channel.dart
TLDR;
I think you should use this...
import 'package:web_socket_channel/web_socket_channel.dart';
...instead of...
import 'package:web_socket_channel/io.dart';
and use it as
WebSocketChannel connect() {
...
return WebSocketChannel.connect(Uri.parse(Path.joinChat));
...
sendChatMessage(WebSocketChannel channel, ChatMessage message) {
Note: I have not tried and tested it!
I think the problem is that you found the right package, but you're using directly IOWebSocketChannel
. That only works on places where dart:io
is available. There's another class in that package, HtmlWebSocketChannel
that only works on the web.