Search code examples
flutterpush-notificationmessaging

How to push data from server to flutter app (send data from server to client without request)


I have a flutter app and it includes something like a chat.

I want to send the message from the server (which is ASP MVC API in my case) to my app so I check my API every 300(ms), while it doesn't make sense; so what the best way I can do to send data from the server to my app?

meanwhile, i can't use firebase (in Syria)

I'm sure that it's a duplicated question but I didn't find my answer anywhere


Solution

  • Edit: this approach is not suitable for messaging apps, since it'll not keep working in background, and also is not suitable for push notification as well.

    Original answer:

    It's ok to use SignalR where it allows you to push data from the server to the client, by calling a function on the client from the server and pass its parameters

    here is some example:

    server code:

    public async void sendMessageToServer(string message, string sender){
        // do something with data
    }
    
    public async void sendMessageToAllClients(string message, string sender){
        await Clients.All.SendAsync("getMessageFromServer",message,sender);
    }
    

    client code(flutter):

    then you must initialize your server connection, usually in main function.

    Example of using signalr_netcore package:

    hubConnection = HubConnectionBuilder().withUrl('serverurl').build();
    await hubConnection.start();
    hubConnection.on("getMessageFromServer", _newMessage);
    

    then you send and receive data:

    _newMessage(List<Object> args) async {
       String message = args[0];
       String sender = args[1];
    }
    
    void sendMessage(){
        String message = 'Hello';
        await hubConnection.invoke("sendMessageToServer", args: <Object>['MyName',message]);
    }