Home > Mobile >  Flutter WebSocket works in web application but not in android emulator
Flutter WebSocket works in web application but not in android emulator

Time:10-06

'final channel = WebSocketChannel.connect( Uri.parse('wss://echo.websocket.org'), );'

  1. can create and connect in web application but can't connect in android emulator

CodePudding user response:

There are two libraries implementing WebSocket class - one that works on web, the other on Andoroid.

You can sort this out by creating a simple factory function. You will need to create several files:

websocket_client_factory.dart

export 'websocket_client_factory_null.dart'
    if (dart.library.html) 'websocket_client_factory_web.dart'
    if (dart.library.io) 'websocket_client_factory_server.dart';

websocket_client_factory_null.dart

import 'package:web_socket_channel/web_socket_channel.dart';

WebSocketChannel makeWsClient(String url) {
  throw 'Platform not supported';
}

websocket_client_factory_server.dart

import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

WebSocketChannel makeWsClient(String url) =>
    IOWebSocketChannel.connect(url, protocols: ['graphql-ws']);

websocket_client_factory_web.dart

import 'package:web_socket_channel/html.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

WebSocketChannel makeWsClient(String url) =>
    HtmlWebSocketChannel.connect(url, protocols: ['graphql-ws']);

Now, from your original file just import the factory file, and call the factory function:

import 'package:./websocket_client_factory.dart';

...
var channel = makeWsClient(wssUrl);

CodePudding user response:

In flutter web application automatically set token but in mobile application need header for authentication Then we need to set token in headers of websocket connection

  • Related