Flutter socket.io connect to nodejs socket.io Flutter socket.io connect to nodejs socket.io flutter flutter

Flutter socket.io connect to nodejs socket.io


Use socket_io_client instead adhara_socket_io.

In pubspec.yaml file add package socket_io_client: ^0.9.4 and flutter_simple_dependency_injection: ^1.0.1

You can create Singleton service like code below (to avoid multiple instance of class):

import 'package:socket_io_client/socket_io_client.dart' as IO;import 'package:tiche_flutter/config.dart';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'));  }}

Create file dependecy_injection.dart

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

Create file app_initializer.dart

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

Add to your main.dart

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

You need to run createSocketConnection function to create connection in your dart file.So, in your file, write code:

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

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

It works for me.