Ali Izadyar
Ali Izadyar

Reputation: 220

Use SignalR on Flutter

Im new to Flutter frameWork

I want to use signalr on flutter to connect to a server and receive notification

below code is how I do it on Java:

            Platform.loadPlatformComponent(new AndroidPlatformComponent());

            Credentials credentials = new Credentials() {
                @Override
                 public void prepareRequest(Request request) {
                    request.addHeader("username", userId);
                }
            };
            String serverUrl = "http://www.xxxxx.org/";
            mHubConnection = new HubConnection(serverUrl);
            mHubConnection.setCredentials(credentials);
            String SERVER_HUB_CHAT = "notificationHub";
            mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
            ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
            SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);

            try {
                signalRFuture.get();
            } catch (Exception ex) {
                UtilFunctions.showToastMessage(getApplicationContext(), ex);
                return;
            }

            String SERVER_METHOD_SEND = "SendNotifications";
            mHubProxy.invoke(SERVER_METHOD_SEND);

            mHubProxy.on("ReceiveNotification", new SubscriptionHandler1<String>() {
                @Override
                public void run(final String string) {
                   ......
                }
            }, String.class);

But Im not able to implement on flutter

Appreciate any help.

Thanks in advance.

Upvotes: 0

Views: 1734

Answers (1)

Milad jalali
Milad jalali

Reputation: 692

add signalr_client 0.1.6

import import 'package:signalr_client/signalr_client.dart';

create a method like this:

void StartSocket() async {

  final serverUrl = "server_url";

  final httpOptions = new HttpConnectionOptions(accessTokenFactory: GetToken); //optional

  hubConnection = HubConnectionBuilder().withUrl(serverUrl, options: httpOptions).build();

  hubConnection.serverTimeoutInMilliseconds = 10 * 60 * 60 * 1000;
  hubConnection.keepAliveIntervalInMilliseconds = 10 * 60 * 60 * 1000;
  await hubConnection.start();

  hubConnection.onclose((error) {
    print("Connection Closed");
    StartSocket();
  });
}

for call a server function use :

hubConnection.invoke("server_function_name");

for define a function that server can call it :

hubConnection.on("client_function_name", (List<Object> parameters) {
  
});

Upvotes: 2

Related Questions