Flutter实时通信插件laravel_echo的使用

Flutter实时通信插件laravel_echo的使用

基本上,这个包是官方Laravel Echo JavaScript库的移植版本。它帮助订阅频道并监听从您的Laravel应用程序广播的事件。

API与官方Echo包相同,因此在官方文档中应该一切正常。

可用的连接器有:

屏幕截图

开始使用

使用socket.io

要使用socket.io,您需要为您的Flutter应用安装socket_io_client

在您的pubspec.yaml文件中:

dependencies:
  ...
  socket_io_client: ^0.9.1
  laravel_echo:

导入socket_io_client

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

使用方法

// 创建Echo实例
Echo echo = new Echo({
  'broadcaster': 'socket.io',
  'client': IO.io,
});

// 监听公共频道
echo.channel('public-channel').listen('PublicEvent', (e) {
  print(e);
});

// 监听私有频道
// 需要认证。有关如何授权频道的详细信息,请参阅指南
echo.private('private-channel').listen('PrivateEvent', (e) {
  print(e);
});

// 监听存在频道
// 需要认证。有关如何授权频道的详细信息,请参阅指南
echo.join('presence-channel')
  .here((users) {
    print(users);
  }).joining((user) {
    print(user);
  }).leaving((user) {
    print(user);
  }).listen('PresenceEvent', (e) {
    print(e);
  });

// 访问socket实例
echo.socket.on('connect', (_) => print('connected'));
echo.socket.on('disconnect', (_) => print('disconnected'));

使用Pusher

要使用Pusher,您需要为您的Flutter应用安装flutter_pusher_client

在您的pubspec.yaml文件中:

dependencies:
  ...
  flutter_pusher_client: ^0.3.1
  laravel_echo: ^0.2.5

导入flutter_pusher_client

import 'package:flutter_pusher_client/flutter_pusher.dart';
PusherOptions options = PusherOptions(
  host: '10.0.2.2',
  port: 6001,
  encrypted: false,
);
FlutterPusher pusher = FlutterPusher('app', options, enableLogging: true);

Echo echo = new Echo({
  'broadcaster': 'pusher',
  'client': pusher,
});

echo.channel('public-channel').listen('PublicEvent', (e) {
  print(e);
});

pusher.on('connect', (_) => print('connect'));
pusher.on('disconnect', (_) => print('disconnect'));

指南

选项

选项 描述 默认值
auth
authEndpoint /broadcasting/auth
broadcaster socket.io
crsfToken
host Socket主机 http://localhost:6001
namespace 事件命名空间 App.Events
其他选项,作为socket参数传递

授权私有频道

为了授权频道请求,我们使用Laravel Passport

在我们的BroadcastServiceProvider.php中,我们需要启用

Broadcast::routes(['middleware' => ['auth:api']]);

然后,在创建Echo实例时包含Authorization头,带有Bearer令牌

echo = new Echo({
  'broadcaster': 'socket.io',
  'client': socket,
  'auth': {
    'headers': {
        'Authorization': 'Bearer $token'
    }
  }
});

示例后端

用于示例应用的后端可以在Kakajan SH的echo-server找到。

包由Kakajan SH提供。

示例代码

以下是完整的示例代码,展示了如何在Flutter应用中使用laravel_echo插件。

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:example/pusher.dart';
import 'package:example/socketio.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return CupertinoApp(
      title: 'Flutter Demo',
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _current = 'socketio';

  [@override](/user/override)
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: CupertinoNavigationBar(
        backgroundColor: Colors.white,
        middle: CupertinoSegmentedControl(
          children: {
            'socketio': Text(
              '  socket.io  ',
              style: TextStyle(fontSize: 14),
            ),
            'pusher': Text(
              'pusher',
              style: TextStyle(fontSize: 14),
            ),
          },
          onValueChanged: (value) {
            setState(() {
              _current = value;
            });
          },
          groupValue: _current,
        ),
      ),
      child: _current == 'socketio' ? SocketioPage() : PusherPage(),
    );
  }
}

更多关于Flutter实时通信插件laravel_echo的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter实时通信插件laravel_echo的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


laravel_echo 是一个用于在 Laravel 应用中实现实时通信的库,通常与 Pusher 或 Socket.IO 等实时通信服务一起使用。在 Flutter 应用中,你可以使用 laravel_echo 插件来实现与 Laravel 后端的实时通信。

以下是如何在 Flutter 中使用 laravel_echo 插件的步骤:

1. 安装依赖

首先,你需要在 pubspec.yaml 文件中添加 laravel_echopusher_client 依赖:

dependencies:
  flutter:
    sdk: flutter
  laravel_echo: ^1.0.0
  pusher_client: ^2.1.0

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

2. 配置 Pusher

在 Laravel 后端,你需要配置 Pusher。首先在 .env 文件中添加 Pusher 的配置:

PUSHER_APP_ID=your-app-id
PUSHER_APP_KEY=your-app-key
PUSHER_APP_SECRET=your-app-secret
PUSHER_APP_CLUSTER=your-app-cluster

然后,在 config/broadcasting.php 中配置广播驱动为 Pusher:

'connections' => [
    'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
            'cluster' => env('PUSHER_APP_CLUSTER'),
            'encrypted' => true,
        ],
    ],
],

3. 在 Flutter 中配置 Laravel Echo

在 Flutter 应用中,初始化 LaravelEcho 并配置 Pusher:

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

void initializeEcho() {
  PusherOptions options = PusherOptions(
    cluster: 'your-app-cluster',
    encrypted: true,
  );

  PusherClient pusherClient = PusherClient(
    'your-app-key',
    options,
    autoConnect: true,
  );

  Echo echo = Echo(
    client: pusherClient,
    broadcaster: EchoBroadcasterType.Pusher,
  );

  echo.connect();
}

4. 监听频道和事件

你可以使用 echo 来监听 Laravel 后端的频道和事件:

void listenToChannel() {
  echo.channel('your-channel-name')
      .listen('YourEventName', (e) {
    print('Event received: ${e.data}');
  });
}

5. 断开连接

当你不再需要实时通信时,可以断开连接:

void disconnectEcho() {
  echo.disconnect();
}

6. 完整示例

以下是一个完整的示例,展示了如何在 Flutter 中使用 laravel_echo

import 'package:flutter/material.dart';
import 'package:laravel_echo/laravel_echo.dart';
import 'package:pusher_client/pusher_client.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  [@override](/user/override)
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Echo echo;

  [@override](/user/override)
  void initState() {
    super.initState();
    initializeEcho();
  }

  void initializeEcho() {
    PusherOptions options = PusherOptions(
      cluster: 'your-app-cluster',
      encrypted: true,
    );

    PusherClient pusherClient = PusherClient(
      'your-app-key',
      options,
      autoConnect: true,
    );

    echo = Echo(
      client: pusherClient,
      broadcaster: EchoBroadcasterType.Pusher,
    );

    echo.connect();

    listenToChannel();
  }

  void listenToChannel() {
    echo.channel('your-channel-name')
        .listen('YourEventName', (e) {
      print('Event received: ${e.data}');
    });
  }

  [@override](/user/override)
  void dispose() {
    echo.disconnect();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Laravel Echo Example'),
      ),
      body: Center(
        child: Text('Listening to real-time events...'),
      ),
    );
  }
}
回到顶部