Connect socket.io to Flutter App

Andrew Kovalchuk
2 min readDec 27, 2019

Very often on projects is a need to connect sockets to exchange data between the FrontEnd and BackEnd side. When you try to realize it on Flutter, you can face a problem to find a package that you need to use. The most popular packages are:

flutter_socket_io
https://pub.dev/packages/flutter_socket_io
adhara_socket_io
https://pub.dev/packages/adhara_socket_io

At the beginning of my assignment, I tried to use both of them, but ran into difficulties of connecting. So I found another package called socket_io_client
https://pub.dev/packages/socket_io_client. It works for me and I advise you how to use it in your application.

In my tutorial I will talk about how to connect sockets to flutter app using socket_io_client.

At first you need to update your pubspec.yaml file:

dependencies:
...
socket_io_client
: ^0.9.4
flutter_simple_dependency_injection: ^1.0.1

You can try to use the last version of this packages, but in this article I will use my working versions.

First of all, we need to create class named SocketService where we will declare our variable and methods to control our socket.

import 'package:socket_io_client/socket_io_client.dart' as IO;

class SocketService {
IO.Socket socket;

createSocketConnection() {
socket = IO.io(config.socketUrl, <String, dynamic>{
'transports': ['websocket'],
});

this.socket.on("connect", (_) => print('Connected'));
this.socket.on("disconnect", (_) => print('Disconnected'));
}
}

If we want to create only one instance of our class, and use it everywhere, we use Dependency Injection and create file dependency_injection.dart.

class DependencyInjection {
Injector initialise(Injector injector) {
injector.map<SocketService>((i) => SocketService(), isSingleton: true);
return injector;
}
}

We need to create one more file called app_initializer.dart and put there initialise function that was called in main() function in main.dart.

import 'package:flutter_simple_dependency_injection/injector.dart';
class AppInitializer {
initialise(Injector injector) async {}
}

The last step to end the connection is to initialize our injector in main.dart .

Injector injector;void main() async {
DependencyInjection().initialise(Injector.getInjector());
injector = Injector.getInjector();
await AppInitializer().initialise(injector);
runApp(MyApp());
}

Now, we can use our variable and methods from our SocketService in our all widgets. You need to inject it to your widget using our injector and use createSocketConnection() function to create our connection to the server.

final SocketService socketService = injector.get<SocketService>();
socketService.createSocketConnection();

If socket connection was created, you will see "Connected" in your terminal.

Thank you for your attention. If you have some problems with connection or questions feel free to ask it in response.

--

--