web_socket_channel throwing Unsupported operation: Platform._version

328

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.

Share:
328
anonymous-dev
Author by

anonymous-dev

Updated on January 02, 2023

Comments

  • anonymous-dev
    anonymous-dev over 1 year

    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?

  • anonymous-dev
    anonymous-dev over 2 years
    Aah I see now and use WebSocketChannel instead of IOWebSocketChannel
  • Ayman Barghout
    Ayman Barghout over 2 years
    Yes, exactly! :) And if you use it for other platforms then use IOWebSocketChannel as well and guard that with kIsWeb like the final comment on the issue says. Happy coding!