chabokpush 1.0.2

  • Readme
  • Changelog
  • Example
  • Installing
  • 74

Chabok Push Client for Flutter #

pub package

Flutter wrapper for chabok library. This client library supports Flutter to use chabok push library. A Wrapper around native library to use chabok functionalities in Flutter environment.

Installation #

For installation refer to Flutter docs and platform specific parts (Android and iOS).

Release Note #

You can find release note here.

Support #

Please visit Issues.

Getting Started - Android #

  1. Add Google and Chabok plugins to build.gradle project level file.
buildscript {
    repositories {
        google()
        jcenter()
	
        maven {
            url "https://plugins.gradle.org/m2/" 
        }
    }
    
    dependencies {
    	classpath "com.android.tools.build:gradle:3.4.2"
	
        classpath "io.chabok.plugin:chabok-services:1.0.0"
        classpath "com.google.gms:google-services:4.3.2"
    }
}
  1. Apply Google and Chabok plugins to build.gradle application level file.
dependencies {
    // your project dependencies
}

apply plugin: 'io.chabok.plugin.chabok-services'
apply plugin: 'com.google.gms.google-services'
  1. Initialize Chabok SDK in your MainApplication.java:
import com.adpdigital.push.AdpPushClient;
import com.adpdigital.push.config.Environment;

import io.flutter.app.FlutterApplication;

public class MainApplication extends FlutterApplication {
    @Override
    public void onCreate() {
        super.onCreate();
	
        AdpPushClient.configureEnvironment(Environment.SANDBOX); // or PRODUCTION
    }
}

Getting started - iOS #

  1. Ensure your iOS projects Pods are up-to-date:
$ cd ios
$ pod install --repo-update
  1. Initialize Chabok SDK in your AppDelegate.m:
#import "AppDelegate.h"
#import <AdpPushClient/AdpPushClient.h>

- (BOOL)application:(UIApplication *)application
            didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [PushClientManager.defaultManager configureEnvironment:Sandbox]; // or PRODUCTION
    
    [GeneratedPluginRegistrant registerWithRegistry:self];
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

Basic Usage #

In your main.dart:

Initialize #

For initializing the Chabok SDK in dart add bellow lines in import section:

import 'package:chabokpush/chabokpush.dart';
import 'package:chabokpush/ChabokEvent.dart';
import 'package:chabokpush/ChabokMessage.dart';

Login user #

To login user in the Chabok service use login method:

ChabokPush.shared.login('USER_ID');

Logout user #

To logout user in the Chabok service use logout method:

ChabokPush.shared.logout();

Set user attributes #

To set user attributes in the Chabok service use setUserAttributes method:

ChabokPush.shared.setUserAttributes(<String, dynamic> {
  'firstName': 'Farbod',
  'lastName': "Samsamipour",
  'age': 28,
  'birthday': new DateTime(1992),
  'isVIP': true,
  'friends': ['hussein', 'habibi']
});

Unset user attributes #

To unset user attributes in the Chabok service user unsetUserAttributes method:

ChabokPush.shared.unsetUserAttributes([
  'isVIP'
]);

Getting message #

To get the Chabok message call setOnMessageCallback:

ChabokPush.shared.setOnMessageCallback((message) {
  var msg = json.decode(message);
  print('Got message = $msg');
});

Getting connection status #

To get connection state call setOnConnectionHandler:

ChabokPush.shared.setOnConnectionHandler((status) {
  print('Connection status = $status');
});

Publish message #

For publishing a message use publish method:

ChabokPush.shared.publish(new ChabokMessage(
  "RECEIVER_USER_ID",
  "CHANNEL_NAME",
  "YOUR MESSAGE")
);

Subscribe on channel #

To subscribe on a channel use subscribe method:

ChabokPush.shared.subscribe('CHANNEL_NAME')
  .then((channel) {
    print('successfully subscribed on channel: $channel');
  }).catchError((error) {
    print('failed to subscribe on channel with error: $error');
  });

Unsubscribe from channel #

To unsubscribe from channel use unSubscribe method:

ChabokPush.shared.subscribe('CHANNEL_NAME')
  .then((channel) {
    print('successfully unsubscribed from channel: $channel');
  }).catchError((error) {
    print('failed to unsubscribe from channel with error: $error');
  });

Track #

To track user interactions use track method :

ChabokPush.shared.track("AddToCart", <String, dynamic> {
  'orderId': 'order_123',
  'orderDate': new DateTime.now(),
  'isBlackFriday': true,
  'orderSize': 69
});

Add tag #

Adding tag to user use addTag method:

ChabokPush.shared.addTag("YOUR_TAG")
  .then((response) {
    print('successfully add tag');
  }).catchError((error) {
      print('failed to add tag with error: $error');
  });

Remove tag #

Removing tag from user use removeTag method:

ChabokPush.shared.removeTag("YOUR_TAG")
  .then((response) {
    print('successfully remove tag');
  }).catchError((error) {
      print('failed to remove tag with error: $error');
  });

1.0.2 #

  • Fix Chabok flutter bridge warning issues.

1.0.1 #

  • Fix flutter warning issues.

1.0.0 #

  • Update Chabok android SDK (v3.1.3)
  • Add Chabok iOS SDK (v2.2.0)
  • Add setOnDeepLinkHandler and setOnReferralHandler methods.
  • Add unsetUserAttributes method.
  • Add incrementUserAttribute and decrementUserAttribute methods.
  • Add addToUserAttributeArray and removeFromUserAttributeArray methods.
  • Add subscribe and unsubscribe methods.
  • Support DateTime type in events and attributes.

0.0.2 #

  • Add setOnMessageCallback method to get chabok message.
  • Add setOnNotificationOpenedHandler method to get notification action.
  • Add setOnShowNotificationHandler method to get notification data before showing notification.
  • Add setOnConnectionHandler method to get Chabok SDK connection status.

0.0.1 #

Android #

  • Add init method.
  • Add register, registerAsGuest and unregister methods.
  • Add publish method.
  • Add addTag and removeTag methods.
  • Add setUserAttributes method.
  • Add getInstallationId and getUserId methods.
  • Add track and trackPurchase methods.

example/lib/main.dart

import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:chabokpush/chabokpush.dart';
import 'package:chabokpush/ChabokEvent.dart';
import 'package:chabokpush/ChabokMessage.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  final TextEditingController userIdController = TextEditingController();
  final TextEditingController tagController = TextEditingController();
  final TextEditingController channelController = TextEditingController();

  Color connectionColor = Colors.red;
  String connectionString = "UNKNOWN";
  String logString = "";

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();

    ChabokPush.shared.getUserId().then((userId) {
      print('userId = $userId');
      userIdController.text = userId;
    });

    ChabokPush.shared.setOnMessageCallback((message) {
      var msg = json.decode(message);
      print('Got message = $msg');

      setState(() {
        logString += '\n' + message;
      });
    });

    ChabokPush.shared.setOnConnectionHandler((status) {
      print('Connection status = $status');

      setState(() {
        connectionString = status;
      });

      switch (status) {
        case 'CONNECTED':
          setState(() {
            connectionColor = Colors.green;
          });
          break;
        case 'CONNECTING':
          setState(() {
            connectionColor = Colors.yellow;
          });
          break;
        case 'DISCONNECTED':
        default:
          setState(() {
            connectionColor = Colors.red;
          });
      }
    });

    ChabokPush.shared.setOnNotificationOpenedHandler((notif) {
      var notifObject = json.decode(notif);
      var actionType = notifObject["actionType"];
      var message = notifObject["message"];
      print('User intract with notification = $actionType\nnotification payload = $message');
    });

    ChabokPush.shared.setOnShowNotificationHandler((notif) {
      var notifObject = json.decode(notif);
      var message = notifObject["message"];
      print('Notification show to user = $message');
    });

    ChabokPush.shared.setOnDeepLinkHandler((deeplink) {
      print('Deeplink = $deeplink');
    });

    ChabokPush.shared.setOnReferralHandler((referralId) {
      print('ReferralId = $referralId');
    });
  }

  @override
  void deactivate() {
    // print('deactivate() invoked.');
    super.deactivate();
  }

  @override
  void dispose() {
    // print('dispose() invoked.');
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // print('state = $state');
  }

  //======================

  _login() {
    ChabokPush.shared.login(userIdController.text.toString())
    .then((response) {
      setState(() {
        var registered = json.decode(response)['registered'].toString();
        logString += '\nregistered response is: $registered';
      });
    }).catchError((error) {
        var userId = userIdController.text.toString();
        setState(() {
          logString += '\nfailed to login for: $userId with error: $error';
        });
    });
  }

  _logout() {
    ChabokPush.shared.logout();
  }

  _addTag() {
    ChabokPush.shared.addTag(tagController.text.toString())
    .then((response) {
      setState(() {
        var count = json.decode(response)['count'].toString();
        logString += '\nsuccessfully add tag with count: $count';
      });
    }).catchError((error) {
        var tag = tagController.text.toString();
        setState(() {
          logString += '\nfailed to add tag: $tag with error: $error';
        });
    });
  }

  _removeTag() {
    ChabokPush.shared.removeTag(tagController.text.toString())
    .then((response) {
      setState(() {
        var count = json.decode(response)['count'].toString();
        logString += '\nsuccessfully remove tag with count: $count';
      });
    }).catchError((error) {
        var tag = tagController.text.toString();
        setState(() {
          logString += '\nfailed to remove tag: $tag with error: $error';
        });
    });
  }

  _setUserAttributes() {
    ChabokPush.shared.setUserAttributes(<String, dynamic> {
      'firstName': 'Farbod',
      'lastName': "Samsamipour",
      'age': 28,
      'birthday': new DateTime(1992),
      'isVIP': true,
      'cars': ['bmw', 'mazda3']
    });
  }

  _unsetUserAttributes() {
    ChabokPush.shared.unsetUserAttributes([
      'firstName',
      'lastName',
      'age',
      'birthday',
      'isVIP',
      'cars'
    ]);
  }

  _addToArray() {
    ChabokPush.shared.addToUserAttributeArray('cars', ['pride']);
  }

  _removeFromArray() {
    ChabokPush.shared.removeFromUserAttributeArray('cars', ['pride']);
  }

  _increment() {
    ChabokPush.shared.incrementUserAttribute('age');
  }

  _decrement() {
    ChabokPush.shared.decrementUserAttribute('age');
  }

  _trackPurchase() {
    var chabokEvent = new ChabokEvent(15000, 'RIAL');
    chabokEvent.setData(<String, dynamic> {
      'purchaseDate': new DateTime.now()
    });
    ChabokPush.shared.trackPurchase("Purchase", chabokEvent);
  }

  _addToCart() {
    ChabokPush.shared.track("AddToCart", <String, dynamic> {
      'orderId': 'oID_123',
      'orderDate': new DateTime.now(),
      'isBlackFriday': true,
      'orderSize': 69
    });
  }

  _like() {
    ChabokPush.shared.track("Like", <String, dynamic> {
      'postId': 'pID_123',
      'likeDate': new DateTime.now(),
      'isOwner': false,
      'likeCount': 85
    });
  }

  _comment() {
    ChabokPush.shared.track("Comment", <String, dynamic> {
      'postId': 'pID_123',
      'commentDate': new DateTime.now(),
      'isOwner': false,
      'commentCount': 85
    });
  }

  _subscribe() {
    ChabokPush.shared.subscribe(channelController.text.toString())
    .then((channel) {
      setState(() {
        logString += '\nsuccessfully subscribed to channel: $channel';
      });
    }).catchError((error) {
        var channel = channelController.text.toString();
        setState(() {
          logString += '\nfailed to subscribe to channel: $channel with error: $error';
        });
    });
  }

  _unsubscribe() {
    ChabokPush.shared.unsubscribe(channelController.text.toString())
    .then((channel) {
      setState(() {
        logString += '\nsuccessfully unsubscribed from channel: $channel';
      });
    }).catchError((error) {
        var channel = channelController.text.toString();
        setState(() {
          logString += '\nfailed to unsubscribe from channel: $channel with error: $error';
        });
    });
  }

  _publishMessage() {
    ChabokPush.shared.publish(new ChabokMessage(
      userIdController.text.toString(),
      "default",
      "Hi dude!")
    );
  }

  @override
  Widget build(BuildContext context) {
    TextStyle style = TextStyle(fontFamily: 'Montserrat', fontSize: 10.0);
    Color color = Theme.of(context).primaryColor;

    Widget connectionSection = Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          Container(
            width: 24,
            height: 24,
            decoration: new BoxDecoration(
              shape: BoxShape.circle,
              color: connectionColor
            )
          ),
          Container(
            padding: EdgeInsets.only(left: 8),
            child: Text(connectionString),
          )
        ]
      )
    );

    Widget loginSection = Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: TextField(
              controller: userIdController,
              decoration: InputDecoration(
                labelText: 'User Id'
              )
            ),
          ),
          Container(
            padding: const EdgeInsets.all(8),
            child: MaterialButton(
              color: color,
              onPressed: _login,
              child: Text("Login",
                textAlign: TextAlign.center,
                style: style.copyWith(
                  color: Colors.white,
                  fontWeight: FontWeight.bold
                )
              )
            )
          ),
          Container(
            padding: const EdgeInsets.all(8),
            child: MaterialButton(
              color: color,
              onPressed: _logout,
              child: Text("Logout",
                textAlign: TextAlign.center,
                style: style.copyWith(
                  color: Colors.white,
                  fontWeight: FontWeight.bold
                )
              )
            ),
          ),
        ],
      ),
    );

    Widget tagSection = Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: TextField(
              controller: tagController,
              decoration: InputDecoration(
                labelText: 'Tag Name'
              )
            ),
          ),
          Container(
            padding: const EdgeInsets.all(8),
            child: MaterialButton(
              color: color,
              onPressed: _addTag,
              child: Text("Add Tag",
                textAlign: TextAlign.center,
                style: style.copyWith(
                  color: Colors.white,
                  fontWeight: FontWeight.bold
                )
              )
            )
          ),
          Container(
            padding: const EdgeInsets.all(8),
            child: MaterialButton(
              color: color,
              onPressed: _removeTag,
              child: Text("Remove Tag",
                textAlign: TextAlign.center,
                style: style.copyWith(
                  color: Colors.white,
                  fontWeight: FontWeight.bold
                )
              )
            ),
          ),
        ],
      ),
    );

    Widget attributeSection = Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          Row(
            children: [
              Text(
                'Attributes:',
                style: TextStyle(
                  fontFamily: 'Montserrat',
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold
                )
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  padding: const EdgeInsets.all(8),
                  child: MaterialButton(
                    color: color,
                    onPressed: _setUserAttributes,
                    child: Text("Set Attributes",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                        color: Colors.white,
                        fontWeight: FontWeight.bold
                      )
                    )
                  )
                )
              ),
              Expanded(
                flex: 1,
                child: Container(
                  padding: const EdgeInsets.all(8),
                  child: MaterialButton(
                    color: color,
                    onPressed: _unsetUserAttributes,
                    child: Text("Unset Attributes",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                        color: Colors.white,
                        fontWeight: FontWeight.bold
                      )
                    )
                  )
                )
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  padding: const EdgeInsets.all(8),
                  child: MaterialButton(
                    color: color,
                    onPressed: _addToArray,
                    child: Text("Add to Array (cars)",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                        color: Colors.white,
                        fontWeight: FontWeight.bold
                      )
                    )
                  )
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(
                  padding: const EdgeInsets.all(8),
                  child: MaterialButton(
                    color: color,
                    onPressed: _removeFromArray,
                    child: Text("Remove from Array (cars)",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                        color: Colors.white,
                        fontWeight: FontWeight.bold
                      )
                    )
                  )
                )
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  padding: const EdgeInsets.all(8),
                  child: MaterialButton(
                    color: color,
                    onPressed: _increment,
                    child: Text("Increment (age)",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                        color: Colors.white,
                        fontWeight: FontWeight.bold
                      )
                    )
                  )
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(
                    padding: const EdgeInsets.all(8),
                    child: MaterialButton(
                      color: color,
                      onPressed: _decrement,
                      child: Text("Decrement (age)",
                        textAlign: TextAlign.center,
                        style: style.copyWith(
                          color: Colors.white,
                          fontWeight: FontWeight.bold
                        )
                      )
                    )
                  )
              )
            ],
          )
        ],
      ),
    );

    Widget eventSection = Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          Row(
            children: [
              Text(
                'Events:',
                style: TextStyle(
                  fontFamily: 'Montserrat',
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold
                )
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  padding: const EdgeInsets.all(8),
                  child: MaterialButton(
                    color: color,
                    onPressed: _addToCart,
                    child: Text("Add to Cart",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                        color: Colors.white,
                        fontWeight: FontWeight.bold
                      )
                    )
                  )
                )
              ),
              Expanded(
                flex: 1,
                child: Container(
                  padding: const EdgeInsets.all(8),
                  child: MaterialButton(
                    color: color,
                    onPressed: _trackPurchase,
                    child: Text("Purchase (15,000)",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                        color: Colors.white,
                        fontWeight: FontWeight.bold
                      )
                    )
                  )
                )
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  padding: const EdgeInsets.all(8),
                  child: MaterialButton(
                    color: color,
                    onPressed: _like,
                    child: Text("Like",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                        color: Colors.white,
                        fontWeight: FontWeight.bold
                      )
                    )
                  )
                )
              ),
              Expanded(
                flex: 1,
                child: Container(
                  padding: const EdgeInsets.all(8),
                  child: MaterialButton(
                    color: color,
                    onPressed: _comment,
                    child: Text("Comment",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                        color: Colors.white,
                        fontWeight: FontWeight.bold
                      )
                    )
                  )
                )
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  padding: const EdgeInsets.all(8),
                  child: MaterialButton(
                    color: color,
                    onPressed: _publishMessage,
                    child: Text("Publish Message (to me!)",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                        color: Colors.white,
                        fontWeight: FontWeight.bold
                      )
                    )
                  )
                ),
              ),
            ],
          ),
        ],
      ),
    );

    Widget subscriptionSection = Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: TextField(
              controller: channelController,
              decoration: InputDecoration(
                labelText: 'Channel Name'
              )
            ),
          ),
          Container(
            padding: const EdgeInsets.all(8),
            child: MaterialButton(
              color: color,
              onPressed: _subscribe,
              child: Text("Subscribe",
                textAlign: TextAlign.center,
                style: style.copyWith(
                  color: Colors.white,
                  fontWeight: FontWeight.bold
                )
              )
            )
          ),
          Container(
            padding: const EdgeInsets.all(8),
            child: MaterialButton(
              color: color,
              onPressed: _unsubscribe,
              child: Text("Unsubscribe",
                textAlign: TextAlign.center,
                style: style.copyWith(
                  color: Colors.white,
                  fontWeight: FontWeight.bold
                )
              )
            ),
          ),
        ],
      ),
    );

    Widget logSection = Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          Row(
            children: [
              Text(
                'Logs:',
                style: TextStyle(
                    fontFamily: 'Montserrat',
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold
                )
              )
            ]
          ),
          Row(
            children: [
              Text(
                logString,
                overflow: TextOverflow.fade,
              )
            ]
          )
        ]
      )
    );

    return MaterialApp(
      title: 'Chabok Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Chabok Flutter Starter App'),
        ),
        body: ListView(
          children: [
            connectionSection,
            Divider(),
            loginSection,
            Divider(),
            tagSection,
            Divider(),
            subscriptionSection,
            Divider(),
            attributeSection,
            Divider(),
            eventSection,
            Divider(),
            logSection
          ],
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  chabokpush: ^1.0.2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

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

3. Import it

Now in your Dart code, you can use:


import 'package:chabokpush/chabokpush.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
48
Health:
Code health derived from static analysis. [more]
99
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
74
Learn more about scoring.

We analyzed this package on Apr 3, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Health issues and suggestions

Document public APIs. (-1 points)

60 out of 60 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test