Reputation: 93
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.
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();
}
Thanks
Upvotes: 1
Views: 860
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!
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