Jack Spicy
Jack Spicy

Reputation: 93

How to use socket hooks with Stream Builder

I want to use real-time data and StreamBuilder with the package called realtime_dart because of my BaaS. Supabase uses this package so I need it too as well. But I don't know how to use Socket hooks in the right way.

Here is the example of the package I am using (realtime_dart)

import 'package:realtime_client/realtime_client.dart';

/// Example to use with Supabase Realtime https://supabase.io/
Future<void> main() async {
  final socket = RealtimeClient('ws://SUPABASE_API_ENDPOINT/realtime/v1',
      params: {'apikey': 'SUPABSE_API_KEY'},
      // ignore: avoid_print
      logger: (kind, msg, data) => {print('$kind $msg $data')});

  final channel = socket.channel('realtime:public');
  channel.on('DELETE', (payload, {ref}) {
    print('channel delete payload: $payload');
  });
  channel.on('INSERT', (payload, {ref}) {
    print('channel insert payload: $payload');
  });

  socket.onMessage((message) => print('MESSAGE $message'));

  // on connect and subscribe
  socket.connect();
  channel.subscribe().receive('ok', (_) => print('SUBSCRIBED'));

  // delay 20s to receive events from server
  await Future.delayed(const Duration(seconds: 20));

  // on unsubscribe and disconnect
  channel.unsubscribe();
  socket.disconnect();
}

How I can use this socket hooks with StreamBuilder?

Thanks

Upvotes: 1

Views: 860

Answers (1)

dshukertjr
dshukertjr

Reputation: 18612

There might be a new stream() feature coming to supabase_dart package, which you can use directly to listen to streams like this:

StreamBuilder<List<Map<String, dynamic>>>(
  stream: supabase.from('chats').stream(),
  builder: (context, snapshot) {
    if (snapshot.connectionState != ConnectionState.active) {
      return preloader;
    }
    final chats = snapshot.data!;
    return ChatCell(chats);
  },
),

It is not yet available, but you can track the PR here

Also, when you use Supabase, you can just use although you can use the individual packages like realtime_client or gotrue, it is easier if you use supabase_flutter package. This comes with everything from auth, realtime storage and postgrest!

Edited on Aug 14

stream() has landed on the newest version of supabase_flutter.

The API changed a bit from what I explained above as you need to call execute() at the end like this:

supabase.from('chats').stream().execute();

Upvotes: 4

Related Questions