Using Pusher in Flutter

Node.js is an open-source, cross-platform JavaScript run-time environment for executing JavaScript code server-side. Historically, JavaScript was used primarily for

What’s Pusher?

Pusher is a hosted service for providing real-time data and functionality to your mobile and web apps easily.

The project that I now working is using Pusher, and while searching for what’s Pusher, I’ve came across a Flutter package. The package is working fine and I’m glad I find it so quick. Thanks to Flutter community and HomeXlabs.

Pusher Websocket Package

This package wraps pusher-websocket-java and pusher-websocket-swift plugins, it’s good to know that it’s unofficial and not maintained by Pusher.

After creating your Pusher account, you need to get key and cluster info for your project. After that, add pusherwebsocketflutter to your pubsec.yaml.

import { TextField } from './TextField/TextField'
import { Select } from './Select/Select'
import { Radio } from './Radio/Radio'

export { TextField, Select, Radio }

Let’s create a file called pusher_service.dart. We will initialize and connect Pusher here, after that we’ll subscribe to a channel and bind events to this channel to listen data.

Channels and Events

Channels and events are Pusher specific terms, don’t confuse them with PlatformChannels. Channels are kind of namespaces to filter and group events. We can define events like something happen in your system or a notification. For example, we can have public channel and message-create event.

I have last event, last connection state and channel in my PusherService class.

class PusherService {
  Event lastEvent;
  String lastConnectionState;
  Channel channel;
}

Now write init, connect, subscribe and unsubcribe methods. In init method, give your key ve cluster. Init method sets up the Pusher, that’s why we need to key and cluster. After that, connect with your connect method, and subscribe to a channel with your subscribe method.

  Future<void> initPusher() async {
    try {
      await Pusher.init(APP_KEY, PusherOptions(cluster: PUSHER_CLUSTER));
    } on PlatformException catch (e) {
      print(e.message);
    }
  }

  void connectPusher() {
    Pusher.connect(
        onConnectionStateChange: (ConnectionStateChange connectionState) async {
      lastConnectionState = connectionState.currentState;
    }, onError: (ConnectionError e) {
      print("Error: ${e.message}");
    });
  }

  Future<void> subscribePusher(String channelName) async {
    channel = await Pusher.subscribe(channelName);
  }

  void unSubscribePusher(String channelName) {
    Pusher.unsubscribe(channelName);
  }
import 'package:flutter/material.dart';
import 'package:medium_article_socket/pusher_service.dart';

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

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    final title = 'Demo';
    return MaterialApp(
      title: title,
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  PusherService pusherService = PusherService();
  
  void initState() {
    pusherService = PusherService();
    pusherService.firePusher('public', 'create');
    super.initState();
  }

  
  void dispose() {
    pusherService.unbindEvent('create');
    super.dispose();
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: StreamBuilder(
          stream: pusherService.eventStream,
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (!snapshot.hasData) {
              return CircularProgressIndicator();
            }
            return Container(
              child: Text(snapshot.data),
            );
          },
        ),
      ),
    );
  }
}

About the author

Hey, I'm Samet, a front end developer. I publish articles and tutorials about modern JavaScript, design, and programming.

Comments