简体   繁体   English

Flutter Pusher Websocket 包不起作用

[英]Flutter Pusher Websocket package not working

I have a backend Laravel application that uses Pusher for notifications.我有一个使用 Pusher 进行通知的后端 Laravel 应用程序。 I would like to show notifications in my Flutter app (both iOS and Android).我想在我的 Flutter 应用程序(iOS 和 Android)中显示通知。 I found that https://pub.dev/packages/pusher_websocket_flutter/ package has the best score, but I can't get it to work.我发现https://pub.dev/packages/pusher_websocket_flutter/包的得分最高,但我无法让它工作。 I've followed this tutorial , and I get no errors (whatever I put for my APP_KEY, which must be wrong), but I never get anything shown.我已经按照本教程进行操作,并且没有出现任何错误(无论我为 APP_KEY 输入什么,都一定是错误的),但是我从未得到任何显示。

Has anyone managed to get this working, or should I switch to firebase?有没有人设法让这个工作,或者我应该切换到firebase?

This is my pusher_service.dart:这是我的 pusher_service.dart:

import 'package:flutter/services.dart';
import 'package:pusher_websocket_flutter/pusher.dart';
import 'dart:async';

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

  StreamController<String> _eventData = StreamController<String>();
  Sink get _inEventData => _eventData.sink;
  Stream get eventStream => _eventData.stream;

  Future<void> initPusher() async {
    try {
      await Pusher.init('XXX', PusherOptions(cluster: 'XX'), enableLogging: true);
      print("Pusher initialized");
    }
    on PlatformException catch (e) {
       print(e.message);
    }
  }

  void connectPusher() {

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

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

  void unSubscribePusher(String channelName) {
    Pusher.unsubscribe(channelName);
  }

  void bindEvent(String eventName) {
    channel.bind(eventName, (last) {
      final String data = last.data;
      _inEventData.add(data);

    });
    print("Pusher data binded");
  }

  void unbindEvent(String eventName) {
    channel.unbind(eventName);
    _eventData.close();
  }

  Future<void> firePusher(String channelName, String eventName) async {
    await initPusher();
    connectPusher();
    await subscribePusher(channelName);
    bindEvent(eventName);
  }

}

My pusher_test.dart:我的 pusher_test.dart:

import 'package:flutter/material.dart';
import 'package:chalet/services/pusher_service.dart';
import 'package:pusher/pusher.dart';
import 'dart:async';

class PusherTest extends StatefulWidget {
  @override
  _PusherTestState createState() => _PusherTestState();
}

class _PusherTestState extends State<PusherTest> {

  PusherService pusherService = PusherService();
  @override
  void initState() {
    pusherService = PusherService();
    pusherService.firePusher('public', 'create');
    testPusher();
    super.initState();

  }

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


  @override
  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),
            );
          },
        ),
      ),
    );
  }
}

I've checked and my snapshot.connectionState is always waiting.我已经检查过,我的 snapshot.connectionState 一直在等待。

Try this:尝试这个:

import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'package:pusher_client/pusher_client.dart';

//instantiate Pusher Class

class PusherController {
  static final PusherController _pusherController =
      PusherController._internal();

  factory PusherController() {
    return _pusherController;
  }

  PusherController._internal();

  PusherClient pusher;
  Channel channel;
  StreamController<String> _eventData = StreamController<String>.broadcast();
  Sink get _inEventData => _eventData.sink;
  Stream get eventStream => _eventData.stream;
  String channelName = "";
  String prevChannelName = "";
  String eventName = "";

  void initPusher() {
    PusherOptions options = PusherOptions(
      cluster: "eu",
    );
    pusher = new PusherClient("key", options,
        autoConnect: true, enableLogging: true);
  }

  void setChannelName(String name) {
    channelName = name;
    print("channelName: ${channelName}");
  }

  void setEventName(String name) {
    eventName = name;
    print("eventName: ${eventName}");
  }

  void subscribePusher() {
    channel = pusher.subscribe(channelName);
    pusher.onConnectionStateChange((state) {
      log("previousState: ${state.previousState}, currentState: ${state.currentState}");
    });

    pusher.onConnectionError((error) {
      log("error: ${error.message}");
    });

    //Bind to listen for events called and sent to channel
    channel.bind(eventName, (PusherEvent event) {
      print("xxxxxxxxx From pusher xxxxxxxxx");
      print('xxxxx This is Event name - $eventName xxxx');
      print('xxxxx This is Event gotten - ${event.data} xxx');

      _inEventData.add(event.data);

      prevChannelName = eventName;
    });
  }


  void connectPusher() {
    pusher.connect();
  }

  void disconnectPusher() async {
    await channel.unbind(eventName);
    await pusher.disconnect();
  }
}



Then use streamBuilder and stream from evenStream.然后使用 streamBuilder 和来自 evenStream 的流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM