ExampleRealtime · Database
Realtime Feed
Build a live feed that updates instantly when records are created, updated, or deleted — without polling.
Setup
Create a posts collection in your dashboard with read: public, write: authenticated, delete: owner. Then connect the realtime subscription after login:
lib/screens/feed_screen.dart
Dart
class FeedScreen extends StatefulWidget {
const FeedScreen({super.key});
@override
State<FeedScreen> createState() => _FeedScreenState();
}
class _FeedScreenState extends State<FeedScreen> {
List<KoolbaseRecord> _posts = [];
StreamSubscription<RealtimeEvent>? _sub;
bool _loading = true;
@override
void initState() {
super.initState();
_load();
// Any post created, updated or deleted: load the feed again.
// Realtime connects as the signed-in person by itself.
_sub = Koolbase.realtime.on(collection: 'posts').listen((_) => _load());
}
Future<void> _load() async {
final result = await Koolbase.db
.collection('posts')
.orderBy('created_at', descending: true)
.limit(50)
.get(fresh: true);
if (!mounted) return;
setState(() {
_posts = result.records;
_loading = false;
});
}
@override
void dispose() {
_sub?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (_loading) return const Center(child: CircularProgressIndicator());
return ListView.builder(
itemCount: _posts.length,
itemBuilder: (_, i) {
final post = _posts[i];
return ListTile(
title: Text(post.data['title'] ?? ''),
subtitle: Text(post.data['body'] ?? ''),
);
},
);
}
}Creating a post
lib/screens/feed_screen.dart
Dart
Future<void> _createPost(String title, String body) async {
// The realtime subscription sees it and the feed reloads
await Koolbase.db.insert(
collection: 'posts',
data: {'title': title, 'body': body, 'published': true},
);
}No manual list update needed
When you insert a record, the realtime subscription receives the change and the feed reloads. You don't need to manually refresh or add it to state after insertion.