Member-only story

Flutter pusher with npusher

Nhan Cao
1 min readJan 15, 2021

To deal with wrong data format response from backend with pusher via Laravel echo

This example works both android and ios

Lib

npusher: ^1.0.3

Example

/// Init pusher
Future<void> initPusher(int eventId) async {
try {
await _pusher.init(
appKey: Config.I.env.pusherKey,
authUrl: '${Config.I.env.apiBaseUrl}/broadcasting/auth',
headers: <String, String>{
'Authorization': 'Bearer ${token.user.bearerToken}',
'Content-Type': 'application/json',
'Accept': 'application/json'
});
_pusher.connect(
(String previousState, String currentState) async {
if (currentState.toLowerCase() == 'connected') {
final NChannel eventChannel =
await _pusher.subscribe('event');
await _pusher.bindEchoPublic(eventChannel, 'OrderCreated',
(NEvent event) {
});
// Remember dispose timer after close screen
final String presenceChannelName = 'event-presence';
final Function(NEvent event) onEventHere = (NEvent event) {
logger.d('onEventHere: $event');
if (Platform.isAndroid) {
_parsePresenceAndroid(event);
} else if (Platform.isIOS) {
_parsePresenceIOS(event);
}
};
_pusherTimer = await _pusher.echoPresencePeriodicStart(
presenceChannelName, onEventHere: onEventHere);
}
},
(String message, String code, String exception) {
logger.d('error: $message');
},
);
} on PlatformException catch (e) {
logger.d('initPusher Error: $e');
initPusher(eventId);
}
}
/// Dispose pusher
Future<void> _disposePusher() async {
_pusherTimer?.cancel();
_pusherTimer = null;
await _pusher.disconnect();
}

--

--

No responses yet