flutter_socket_io 0.4.3

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 89

flutter_socket_io

Flutter Socket IO Plugin, supported Android + iOS (iOS installation guide is coming soon)

How to install on iOS

    1. Copy the folder example/ios/Runner/SocketObj to ${PROJECT_ROOT}/ios/Runner/
    1. Replace the ${PROJECT_ROOT}/ios/Runner/AppDelegate.m with example/ios/Runner/AppDelegate.m. (Notice: You should merge the old one in your project to merge with the new from this plugin if you have some change on that file)
    1. Open ${PROJECT_ROOT}/ios/Podfile, paste this line pod 'Socket.IO-Client-Swift', '~> 13.3.0' before the end of target 'Runner' do block
    1. Run and Enjoy the plugin :)

Use the plugin

1. Add the following import to your Dart code:

import  'package:flutter_socket_io/flutter_socket_io.dart';

2. SocketIOManager: to manage (create/destroy) list of SocketIO

Create SocketIO with SocketIOManager:

SocketIO socketIO = SocketIOManager().createSocketIO("http://127.0.0.1:3000", "/chat", query: "userId=21031", socketStatusCallback: _socketStatus);  

Destroy SocketIO with socketIOManager:

SocketIOManager().destroySocket(socketIO);  

3. SocketIO:

Get Id (Url + Namespace) of the socket

String getId();


Create a new socket and connects the client

Future<void> connect();


Init socket before doing anything with socket

Future<void> init();


Subscribe to a channel with a callback

 Future<void> subscribe(String event, Function callback); 


Unsubscribe from a channel. When no callback is provided, unsubscribe all subscribers of the channel. Otherwise, unsubscribe only the callback passed in

Future<void> unSubscribe(String event, [Function callback]); 


Send a message via a channel (i.e. event, the native code will convert string message to JsonObject before sending)

Future<void> sendMessage(String event, dynamic message, [Function callback]);


Disconnect from the socket

Future<void> disconnect(); 


Unsubscribe all subscribers from all channels

Future<void> unSubscribesAll();


4. Example: Link

SocketIO socketIO;
_connectSocket01() { 
	//update your domain before using  
	 socketIO = SocketIOManager().createSocketIO("http://127.0.0.1:3000", "/chat", query: "userId=21031", socketStatusCallback: _socketStatus); 

	//call init socket before doing anything 
	socketIO.init(); 

	//subscribe event
	socketIO.subscribe("socket_info", _onSocketInfo); 

	//connect socket 
	socketIO.connect(); 
}

_socketStatus(dynamic data) { 
	print("Socket status: " + data); 
}

_subscribes() { 
	if (socketIO != null) { 
		socketIO.subscribe("chat_direct", _onReceiveChatMessage); 
	} 
}

void _onReceiveChatMessage(dynamic message) { 
	print("Message from UFO: " + message); 
}

void _sendChatMessage(String msg) async { 
	if (socketIO != null) { 
		String jsonData = '{"message":{"type":"Text","content": ${(msg != null && msg.isNotEmpty) ? '"${msg}"' : '"Hello SOCKET IO PLUGIN :))"'},"owner":"589f10b9bbcd694aa570988d","avatar":"img/avatar-default.png"},"sender":{"userId":"589f10b9bbcd694aa570988d","first":"Ha","last":"Test 2","location":{"lat":10.792273999999999,"long":106.6430356,"accuracy":38,"regionId":null,"vendor":"gps","verticalAccuracy":null},"name":"Ha Test 2"},"receivers":["587e1147744c6260e2d3a4af"],"conversationId":"589f116612aa254aa4fef79f","name":null,"isAnonymous":null}'; 
		socketIO.sendMessage("chat_direct", jsonData, _onReceiveChatMessage); 
	}
 }

_destroySocket() { 
	if (socketIO != null) { 
		SocketIOManager().destroySocket(socketIO); 
	} 
}



0.4.3

  • Changed: - init with query option
  • Fixed bug: - added forceNew to create socket instance

0.4.2

  • Fixed bug: checked NULL data received before calling back when using sendMessage function* Fixed bug: checked NULL data received from server before calling back when using sendMessage function

0.4.1

  • Changed: changed android dependency from "com.github.nkzawa:socket.io-client:0.3.0" to official socket.io "io.socket:socket.io-client:1.0.0"

0.4.0

  • Added: The guide for installing this plugin on iOS
  • Added: MIT LICENSE

0.3.8

  • Fixed bugs.

0.3.7

  • Updated documentation

0.3.3

  • Fixed bugs: iOS don't create new SocketManger (with the same domain) if it already existed.

0.3.2

  • Fixed bugs.

0.3.0

  • Supported iOS (Testing).

0.2.0

  • Added function: init() socket (please call this function before doing anything with socket)

0.1.1

  • Refactor code.

0.1.0

  • Fixed bugs.

0.0.21

  • Fixed bugs.

0.0.20

  • Fixed bugs.

0.0.19

  • Fixed bugs.

0.0.18

  • Fixed bugs.

0.0.17

  • Set transports = new String[]{WebSocket.NAME};

0.0.16

  • Fixed bugs.

0.0.15

  • Fixed bugs.
  • Added 'String query' param [optional] when calling connect function

0.0.14

  • Fixed bugs.

0.0.12

  • Fixed bugs.

0.0.11

  • Fixed bugs.
  • Added features: supported calling connect/subscribes/unSubscribes/sendMessage with Flutter's callback Function.
  • Supported OS:
    • Android
    • iOS: COMING SOON

0.0.8

  • Initial release.
  • Supported:
    • Android
    • iOS: coming soon

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_socket_io/flutter_socket_io.dart';
import 'package:flutter_socket_io/socket_io_manager.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in IntelliJ). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  var mTextMessageController = new TextEditingController();
  SocketIO socketIO;
  SocketIO socketIO02;

  @override
  void initState() {
    super.initState();
  }

  _connectSocket01() {
    //update your domain before using
    /*socketIO = new SocketIO("http://127.0.0.1:3000", "/chat",
        query: "userId=21031", socketStatusCallback: _socketStatus);*/
    socketIO = SocketIOManager().createSocketIO("http://127.0.0.1:3000", "/chat", query: "userId=21031", socketStatusCallback: _socketStatus);

    //call init socket before doing anything
    socketIO.init();

    //subscribe event
    socketIO.subscribe("socket_info", _onSocketInfo);

    //connect socket
    socketIO.connect();
  }

  _connectSocket02() {
    socketIO02 = SocketIOManager().createSocketIO("http://127.0.0.1:3000", "/map", query: "userId=21031", socketStatusCallback: _socketStatus02);

    //call init socket before doing anything
    socketIO02.init();

    //subscribe event
    socketIO02.subscribe("socket_info", _onSocketInfo02);

    //connect socket
    socketIO02.connect();
  }

  _onSocketInfo(dynamic data) {
    print("Socket info: " + data);
  }

  _socketStatus(dynamic data) {
    print("Socket status: " + data);
  }

  _onSocketInfo02(dynamic data) {
    print("Socket 02 info: " + data);
  }

  _socketStatus02(dynamic data) {
    print("Socket 02 status: " + data);
  }

  _subscribes() {
    if (socketIO != null) {
      socketIO.subscribe("chat_direct", _onReceiveChatMessage);
    }
  }

  _unSubscribes() {
    if (socketIO != null) {
      socketIO.unSubscribe("chat_direct", _onReceiveChatMessage);
    }
  }

  _reconnectSocket() {
    if (socketIO == null) {
      _connectSocket01();
    } else {
      socketIO.connect();
    }
  }

  _disconnectSocket() {
    if (socketIO != null) {
      socketIO.disconnect();
    }
  }

  _destroySocket() {
    if (socketIO != null) {
      SocketIOManager().destroySocket(socketIO);
    }
  }

  void _sendChatMessage(String msg) async {
    if (socketIO != null) {
      String jsonData =
          '{"message":{"type":"Text","content": ${(msg != null && msg.isNotEmpty) ? '"${msg}"' : '"Hello SOCKET IO PLUGIN :))"'},"owner":"589f10b9bbcd694aa570988d","avatar":"img/avatar-default.png"},"sender":{"userId":"589f10b9bbcd694aa570988d","first":"Ha","last":"Test 2","location":{"lat":10.792273999999999,"long":106.6430356,"accuracy":38,"regionId":null,"vendor":"gps","verticalAccuracy":null},"name":"Ha Test 2"},"receivers":["587e1147744c6260e2d3a4af"],"conversationId":"589f116612aa254aa4fef79f","name":null,"isAnonymous":null}';
      socketIO.sendMessage("chat_direct", jsonData, _onReceiveChatMessage);
    }
  }

  void socketInfo(dynamic message) {
    print("Socket Info: " + message);
  }

  void _onReceiveChatMessage(dynamic message) {
    print("Message from UFO: " + message);
  }

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed(
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  void _showToast() {
    _sendChatMessage(mTextMessageController.text);
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return new Scaffold(
      appBar: new AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: new Text(widget.title),
      ),
      body: new Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: new Column(
          // Column is also layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug paint" (press "p" in the console where you ran
          // "flutter run", or select "Toggle Debug Paint" from the Flutter tool
          // window in IntelliJ) to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new RaisedButton(
              child:
                  const Text('CONNECT  SOCKET 01', style: TextStyle(color: Colors.white)),
              color: Theme.of(context).accentColor,
              elevation: 0.0,
              splashColor: Colors.blueGrey,
              onPressed: () {
                _connectSocket01();
//                _sendChatMessage(mTextMessageController.text);
              },
            ),
            new RaisedButton(
              child:
              const Text('CONNECT SOCKET 02', style: TextStyle(color: Colors.white)),
              color: Theme.of(context).accentColor,
              elevation: 0.0,
              splashColor: Colors.blueGrey,
              onPressed: () {
                _connectSocket02();
//                _sendChatMessage(mTextMessageController.text);
              },
            ),
            new RaisedButton(
              child: const Text('SEND MESSAGE', style: TextStyle(color: Colors.white)),
              color: Theme.of(context).accentColor,
              elevation: 0.0,
              splashColor: Colors.blueGrey,
              onPressed: () {
                _showToast();
//                _sendChatMessage(mTextMessageController.text);
              },
            ),
            new RaisedButton(
              child: const Text('SUBSCRIBES',
                  style: TextStyle(color: Colors.white)),
              color: Theme.of(context).accentColor,
              elevation: 0.0,
              splashColor: Colors.blueGrey,
              onPressed: () {
                _subscribes();
//                _sendChatMessage(mTextMessageController.text);
              },
            ),
            new RaisedButton(
              child: const Text('UNSUBSCRIBES',
                  style: TextStyle(color: Colors.white)),
              color: Theme.of(context).accentColor,
              elevation: 0.0,
              splashColor: Colors.blueGrey,
              onPressed: () {
                _unSubscribes();
//                _sendChatMessage(mTextMessageController.text);
              },
            ),
            new RaisedButton(
              child: const Text('RECONNECT',
                  style: TextStyle(color: Colors.white)),
              color: Theme.of(context).accentColor,
              elevation: 0.0,
              splashColor: Colors.blueGrey,
              onPressed: () {
                _reconnectSocket();
//                _sendChatMessage(mTextMessageController.text);
              },
            ),
            new RaisedButton(
              child: const Text('DISCONNECT',
                  style: TextStyle(color: Colors.white)),
              color: Theme.of(context).accentColor,
              elevation: 0.0,
              splashColor: Colors.blueGrey,
              onPressed: () {
                _disconnectSocket();
//                _sendChatMessage(mTextMessageController.text);
              },
            ),
            new RaisedButton(
              child:
                  const Text('DESTROY', style: TextStyle(color: Colors.white)),
              color: Theme.of(context).accentColor,
              elevation: 0.0,
              splashColor: Colors.blueGrey,
              onPressed: () {
                _destroySocket();
//                _sendChatMessage(mTextMessageController.text);
              },
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_socket_io: ^0.4.3

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_socket_io/flutter_socket_io.dart';
  
Version Uploaded Documentation Archive
0.4.3 Sep 16, 2018 Go to the documentation of flutter_socket_io 0.4.3 Download flutter_socket_io 0.4.3 archive
0.4.2 Sep 16, 2018 Go to the documentation of flutter_socket_io 0.4.2 Download flutter_socket_io 0.4.2 archive
0.4.1 Sep 11, 2018 Go to the documentation of flutter_socket_io 0.4.1 Download flutter_socket_io 0.4.1 archive
0.4.0 Sep 10, 2018 Go to the documentation of flutter_socket_io 0.4.0 Download flutter_socket_io 0.4.0 archive
0.3.8 Sep 1, 2018 Go to the documentation of flutter_socket_io 0.3.8 Download flutter_socket_io 0.3.8 archive
0.3.7 Sep 1, 2018 Go to the documentation of flutter_socket_io 0.3.7 Download flutter_socket_io 0.3.7 archive
0.3.6 Sep 1, 2018 Go to the documentation of flutter_socket_io 0.3.6 Download flutter_socket_io 0.3.6 archive
0.3.5 Sep 1, 2018 Go to the documentation of flutter_socket_io 0.3.5 Download flutter_socket_io 0.3.5 archive
0.3.4 Sep 1, 2018 Go to the documentation of flutter_socket_io 0.3.4 Download flutter_socket_io 0.3.4 archive
0.3.3 Aug 31, 2018 Go to the documentation of flutter_socket_io 0.3.3 Download flutter_socket_io 0.3.3 archive

All 38 versions...

Popularity:
Describes how popular the package is relative to other packages. [more]
87
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
89
Learn more about scoring.

We analyzed this package on Oct 10, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.4
  • Flutter: 0.9.5

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Format lib/flutter_socket_io.dart.

Run flutter format to format lib/flutter_socket_io.dart.

Format lib/socket_io_manager.dart.

Run flutter format to format lib/socket_io_manager.dart.

Maintenance suggestions

The description is too short. (-20 points)

Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.28.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11
meta 1.1.6
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8