Flutter Laravel Echo集成插件laravel_echo_null的使用

发布于 1周前 作者 ionicwang 来自 Flutter

Flutter Laravel Echo集成插件laravel_echo_null的使用

Getting started

Important information before using

laravel_echo_null 包依赖以下包:

Package Version URL Source
socket_io_client 3.0.2 pub.dev
pusher_client_socket 0.0.3 pub.dev
fixed-laravel-echo-server 0.1.4 npm

将这些依赖添加到 pubspec.yaml 文件中:

dependencies:
  socket_io_client: ^3.0.2
  pusher_client_socket: ^0.0.3

请注意,laravel_echo_null 包需要 socket_io_client 版本 2.0.2。此外,为了确保与包的兼容性,请使用 fixed-laravel-echo-server 版本 0.0.1,它可以在 npm 上找到。可以通过运行以下命令全局安装:

npm i -g [@abdopr](/user/abdopr)/fixed-laravel-echo-server

更多详细信息请参阅 fixed-laravel-echo-server 的官方文档。

确保正确添加这些依赖并按照说明将其包含在项目中。

Importing

导入 laravel_echo_null 包:

import 'package:laravel_echo_null/laravel_echo_null.dart';

Initializing

使用连接器进行初始化

Socket IO

import 'package:socket_io_client/socket_io_client.dart' as IO;

Echo<IO.Socket, SocketIoChannel> echo = Echo<IO.Socket, SocketIoChannel>(SocketIoConnector(
  'http://localhost:6001', // String: host
  nameSpace: 'nameSpace', // String?: namespace
  autoConnect: false, // bool: client connection automatically
  authHeaders: {
    'Authorization': 'Bearer token'
  },
  moreOptions: {// Map: more io options
    'transports': ['websocket']
  },
));

Pusher

import 'package:pusher_client_socket/pusher_client_socket.dart' as PUSHER;

Echo<PUSHER.PusherClient, PusherChannel> echo = Echo<PUSHER.PusherClient, PusherChannel>(PusherConnector(
  'PUSHER_APP_KEY',
  authEndPoint: 'http://localhost/broadcasting/auth', // String?: auth host
  authHeaders: { // authenticate headers
    'Authorization': 'Bearer $token',
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  cluster: 'PUSHER_CLUSTER', // String?: pusher cluster
  wsPort: 80,
  wssPort: 443,
  encrypted: true,
  activityTimeout: 120000,
  pongTimeout: 30000,
  maxReconnectionAttempts: 6,
  reconnectGap: Duration(seconds: 2),
  enableLogging: true,
  autoConnect: false, // bool: client connection automatically
  nameSpace: 'nameSpace',
));

Pusher With Laravel/Reverb

import 'package:pusher_client_socket/pusher_client_socket.dart' as PUSHER;

Echo<PUSHER.PusherClient, PusherChannel> echo = Echo<PUSHER.PusherClient, PusherChannel>(PusherConnector(
  'PUSHER_APP_KEY',
  authEndPoint: 'http://localhost/broadcasting/auth', // String?: auth host
  authHeaders: { // authenticate headers
    'Authorization': 'Bearer $token',
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  host: 'localhost',
  wsPort: 6001,
  encrypted: false,
  activityTimeout: 120000,
  pongTimeout: 30000,
  enableLogging: true,
  autoConnect: false, // bool: client connection automatically
  nameSpace: 'nameSpace',
));

简单初始化

Socket IO

import 'package:socket_io_client/socket_io_client.dart';

Echo<IO.Socket, SocketIoChannel> echo = Echo.socket(
  'http://localhost:6001', // String: host
  nameSpace: 'nameSpace', // String?: namespace
  autoConnect: false, // bool: client connection automatically
  authHeaders: {
    'Authorization': 'Bearer token'
  },
  moreOptions: {// Map: more io options
    'transports': ['websocket']
  },
);

Pusher

import 'package:pusher_client_socket/pusher_client_socket.dart';

Echo<PUSHER.PusherClient, PusherChannel> echo = Echo.pusher(
  'PUSHER_APP_KEY',
  authEndPoint: 'http://localhost/broadcasting/auth', // String?: auth host
  authHeaders: { // authenticate headers
    'Authorization': 'Bearer $token',
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  cluster: 'PUSHER_CLUSTER', // String?: pusher cluster
  wsPort: 80,
  wssPort: 443,
  encrypted: true,
  activityTimeout: 120000,
  pongTimeout: 30000,
  maxReconnectionAttempts: 6,
  reconnectGap: Duration(seconds: 2),
  enableLogging: true,
  autoConnect: false, // bool: client connection automatically
  nameSpace: 'nameSpace',
);

Channels

// 公共频道
Channel publicChannel = echo.channel('my-channel');
publicChannel.listen('MyEvent', (data) {
  print(data);
});

// 私有频道
PrivateChannel privateChannel = echo.private('my-channel.1')
privateChannel.listen('MyEvent', (data) {
  print(data);
});

// 加密私有频道
PrivateEncryptedChannel privateEncryptedChannel = echo.privateEncrypted('my-channel.1')
privateEncryptedChannel.listen('MyEvent', (data) {
  print(data);
});

// 存在频道
PresenceChannel presenceChannel = echo.join('presence-channel');
presenceChannel.listen((data) {
  print(data);
});

示例代码

以下是一个简单的Flutter应用程序示例,演示如何使用 laravel_echo_null 包:

import 'package:flutter/material.dart';
import 'home.dart';

void main() => runApp(const App());

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) => const MaterialApp(
        home: Home(),
      );
}

home.dart 文件中,您可以添加更多的逻辑来处理事件监听和频道连接:

import 'package:flutter/material.dart';
import 'package:laravel_echo_null/laravel_echo_null.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  late Echo<IO.Socket, SocketIoChannel> echo;

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

    echo = Echo.socket(
      'http://localhost:6001',
      nameSpace: 'nameSpace',
      autoConnect: false,
      authHeaders: {
        'Authorization': 'Bearer token'
      },
      moreOptions: {
        'transports': ['websocket']
      },
    );

    echo.channel('my-channel').listen('MyEvent', (data) {
      print('Received data: $data');
    });

    echo.connect();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Laravel Echo Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // 发送事件或执行其他操作
          },
          child: const Text('Send Event'),
        ),
      ),
    );
  }

  @override
  void dispose() {
    echo.disconnect();
    super.dispose();
  }
}

以上是关于 laravel_echo_null 包的基本使用指南和示例代码。希望对您有所帮助!


更多关于Flutter Laravel Echo集成插件laravel_echo_null的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Laravel Echo集成插件laravel_echo_null的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在处理Flutter与Laravel Echo的集成时,laravel_echo_null插件通常用于在没有实际WebSocket服务器(如Pusher或Socket.IO)的情况下进行开发和测试。这个插件基本上是一个空实现,不会发送或接收任何WebSocket消息。然而,它允许你在Flutter应用中配置和使用Laravel Echo,而无需实际的WebSocket服务器。

以下是如何在Flutter项目中集成laravel_echo_null插件,并配置Laravel Echo的示例代码。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加laravel_echolaravel_echo_null依赖:

dependencies:
  flutter:
    sdk: flutter
  laravel_echo: ^x.y.z  # 替换为最新版本号
  laravel_echo_null: ^x.y.z  # 替换为最新版本号

然后运行flutter pub get来安装这些依赖。

2. 配置Laravel Echo

在你的Flutter项目的某个合适位置(如lib/services/echo_config.dart),配置Laravel Echo以使用laravel_echo_null连接器:

import 'package:laravel_echo/laravel_echo.dart';
import 'package:laravel_echo_null/laravel_echo_null.dart';

class EchoConfig {
  static Echo create() {
    // Laravel Echo的配置信息
    var broadcaster = 'null'; // 使用null广播器
    var key = 'your-laravel-echo-server-key'; // Laravel Echo服务器的key(对于null连接器来说这个key不会被使用)
    var cluster = 'your-cluster'; // Laravel Echo服务器的cluster(对于null连接器来说这个cluster不会被使用)
    var forceTLS = false; // 是否强制使用TLS

    // 创建一个Echo实例,使用laravel_echo_null连接器
    return Echo({
      broadcaster: broadcaster,
      key: key,
      cluster: cluster,
      forceTLS: forceTLS,
      connector: new NullConnector()
    });
  }
}

3. 使用Echo

现在你可以在你的Flutter应用中使用配置好的Echo实例了。例如,监听一个频道上的事件:

import 'package:flutter/material.dart';
import 'echo_config.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Laravel Echo Example'),
        ),
        body: EchoExample(),
      ),
    );
  }
}

class EchoExample extends StatefulWidget {
  @override
  _EchoExampleState createState() => _EchoExampleState();
}

class _EchoExampleState extends State<EchoExample> {
  @override
  void initState() {
    super.initState();
    // 获取Echo实例并监听频道
    var echo = EchoConfig.create();
    var channel = echo.channel('test-channel');

    channel.listen('.client-event', (e) {
      // 处理接收到的事件
      print('Received client event: $e');
    });

    // 发送一个客户端事件(仅用于测试,null连接器不会实际发送)
    channel.trigger('.client-event', {'message': 'Hello from Flutter!'});
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('Listening for events on test-channel...'),
    );
  }
}

在这个示例中,我们创建了一个Echo实例,监听名为test-channel的频道上的.client-event事件。然而,由于我们使用的是laravel_echo_null连接器,这些事件不会被实际发送或接收。这对于在没有实际WebSocket服务器的情况下进行开发和测试非常有用。

请注意,在实际部署到生产环境时,你应该使用适当的WebSocket服务器(如Pusher或Socket.IO)并相应地配置Laravel Echo。

回到顶部