Stream Supabase Chat SDK

A plug-and-play Flutter SDK for integrating Stream Chat with Supabase authentication. This package provides ready-to-use chat UI components with extensive customization options.

Features

  • 🚀 Quick Setup: Get chat running in minutes
  • 🔐 Integrated Auth: Seamless Supabase + Stream Chat authentication
  • 🎨 Fully Customizable: Customize every aspect of the UI
  • 📱 Production Ready: Built on Stream Chat Flutter SDK
  • 💬 Complete Chat Features: 1-on-1 and group chats
  • 🔌 Plug and Play: Minimal configuration required

Installation

Add to your pubspec.yaml:

dependencies:
  stream_supabase_chat: ^1.0.5

Then run:

flutter pub get

Prerequisites

1. Supabase Edge Function

Create a Supabase Edge Function to generate Stream tokens:

// supabase/functions/generate-stream-token/index.ts
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
import { StreamChat } from 'https://esm.sh/stream-chat@8'

serve(async (req) => {
  try {
    const supabaseClient = createClient(
      Deno.env.get('SUPABASE_URL') ?? '',
      Deno.env.get('SUPABASE_ANON_KEY') ?? '',
      { global: { headers: { Authorization: req.headers.get('Authorization')! } } }
    )

    const { data: { user } } = await supabaseClient.auth.getUser()
    
    if (!user) {
      throw new Error('Not authenticated')
    }

    const serverClient = StreamChat.getInstance(
      Deno.env.get('STREAM_API_KEY')!,
      Deno.env.get('STREAM_SECRET_KEY')!
    )

    const token = serverClient.createToken(user.id)

    return new Response(
      JSON.stringify({ token }),
      { headers: { 'Content-Type': 'application/json' } }
    )
  } catch (error) {
    return new Response(
      JSON.stringify({ error: error.message }),
      { status: 400, headers: { 'Content-Type': 'application/json' } }
    )
  }
})

2. Environment Variables

Add to Supabase Edge Function secrets:

  • STREAM_API_KEY
  • STREAM_SECRET_KEY

Quick Start

1. Initialize the SDK

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Supabase
  await Supabase.initialize(
    url: 'YOUR_SUPABASE_URL',
    anonKey: 'YOUR_SUPABASE_ANON_KEY',
  );

  // Initialize Stream Chat
  final config = ChatConfig(
    streamApiKey: 'YOUR_STREAM_API_KEY',
    supabaseUrl: 'YOUR_SUPABASE_URL',
    supabaseAnonKey: 'YOUR_SUPABASE_ANON_KEY',
    debugMode: true,
  );

  StreamChatService().initialize(config);

  runApp(const MyApp());
}

2. Wrap Your App

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My Chat App',
      theme: ThemeData(primarySwatch: Colors.blue),
      builder: (context, child) {
        return ChatAppWrapper(
          child: child!,
        );
      },
      home: const LoginPage(),
    );
  }
}

Important: Use the builder parameter of MaterialApp to wrap with ChatAppWrapper. This ensures the StreamChat theme is available throughout your app.

3. Use Pre-built Screens

// Login Page - Already included
Navigator.push(
  context,
  MaterialPageRoute(builder: (_) => const LoginPage()),
);

// Home Screen with Channel List
Navigator.push(
  context,
  MaterialPageRoute(builder: (_) => const ChatHomeScreen()),
);

// Users List (Start New Chat)
Navigator.push(
  context,
  MaterialPageRoute(builder: (_) => const UsersListPage()),
);

Customization

Customize Channel Page

final channelConfig = ChannelPageConfig(
  showBackButton: true,
  showCommandsButton: false,
  backgroundColor: Colors.grey[100],
  appBarActions: [
    IconButton(
      icon: const Icon(Icons.video_call),
      onPressed: () => print('Video call'),
    ),
  ],
  messageInputActions: (context, defaultActions) => [
    IconButton(
      icon: const Icon(Icons.camera_alt),
      onPressed: () => print('Open camera'),
    ),
  ],
);

// Use in navigation
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (_) => StreamChannel(
      channel: channel,
      child: ChannelPage(config: channelConfig),
    ),
  ),
);

Customize Channel List

final channelListConfig = ChannelListConfig(
  title: 'My Chats',
  limit: 30,
  channelTileBuilder: (context, channel) {
    return ListTile(
      leading: StreamChannelAvatar(channel: channel),
      title: StreamChannelName(channel: channel),
      subtitle: Text('Custom subtitle'),
      trailing: const Icon(Icons.arrow_forward_ios),
    );
  },
  emptyStateWidget: const Center(
    child: Text('No conversations yet. Start chatting!'),
  ),
);

// Use with ChatHomeScreen
ChatHomeScreen(config: channelListConfig)

Custom Message Builder

final channelConfig = ChannelPageConfig(
  messageBuilder: (context, details, messages) {
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: details.message.user?.id == currentUserId 
          ? Colors.blue[100] 
          : Colors.grey[200],
        borderRadius: BorderRadius.circular(12),
      ),
      child: Text(details.message.text ?? ''),
    );
  },
);

Custom Theme

final customTheme = StreamChatThemeData(
  colorTheme: StreamColorTheme.dark(),
  channelPreviewTheme: StreamChannelPreviewThemeData(
    avatarTheme: StreamAvatarThemeData(
      borderRadius: BorderRadius.circular(8),
    ),
  ),
);

final channelConfig = ChannelPageConfig(
  streamTheme: customTheme,
);

Customize Users List

final usersConfig = UsersListConfig(
  title: 'Select Contact',
  subtitle: 'Choose a user to start chatting',
  userTileBuilder: (context, user) {
    return Card(
      child: ListTile(
        leading: UserAvatar(user: user),
        title: Text(user.name ?? 'Unknown'),
        subtitle: Text(user.extraData['email'] as String? ?? ''),
        trailing: const Icon(Icons.chat_bubble_outline),
      ),
    );
  },
);

UsersListPage(config: usersConfig)

Advanced Usage

Custom Authentication Flow

class CustomAuthScreen extends StatelessWidget {
  Future<void> _customSignIn() async {
    final authService = ChatAuthService();
    
    await authService.signInAndConnectStream(
      email: email,
      password: password,
    );
    
    // Navigate to home
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (_) => const ChatHomeScreen()),
    );
  }

  @override
  Widget build(BuildContext context) {
    // Your custom UI
  }
}

Direct Service Access

// Access Stream Chat Service
final streamService = StreamChatService();
final client = streamService.client;

// Create custom channel
final channel = await streamService.createGroupChannel(
  groupName: 'My Custom Group',
  memberIds: ['user1', 'user2', 'user3'],
);

// Fetch users
final users = await streamService.fetchUsers(currentUserId);

// Access Auth Service
final authService = ChatAuthService();
final isAuth = authService.isAuthenticated;
final userId = authService.currentUserId;

Handle Session Persistence

class SplashScreen extends StatefulWidget {
  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    _checkSession();
  }

  Future<void> _checkSession() async {
    final authService = ChatAuthService();

    if (authService.isAuthenticated) {
      try {
        await authService.reconnectStream();
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (_) => const ChatHomeScreen()),
        );
      } catch (e) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (_) => const LoginPage()),
        );
      }
    } else {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (_) => const LoginPage()),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(child: CircularProgressIndicator()),
    );
  }
}

Complete Example

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Supabase.initialize(
    url: 'YOUR_SUPABASE_URL',
    anonKey: 'YOUR_SUPABASE_ANON_KEY',
  );

  final config = ChatConfig(
    streamApiKey: 'YOUR_STREAM_API_KEY',
    supabaseUrl: 'YOUR_SUPABASE_URL',
    supabaseAnonKey: 'YOUR_SUPABASE_ANON_KEY',
  );

  StreamChatService().initialize(config);

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My Chat App',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: ChatAppWrapper(
        child: const LoginPage(),
      ),
    );
  }
}

API Reference

Core Classes

  • ChatConfig - SDK configuration
  • StreamChatService - Stream Chat operations
  • ChatAuthService - Authentication management

UI Screens

  • LoginPage - Login screen
  • RegisterPage - Registration screen
  • ChatHomeScreen - Channel list screen
  • ChannelPage - Chat conversation screen
  • UsersListPage - User selection screen
  • CreateGroupPage - Group creation screen

Configuration Classes

  • ChannelPageConfig - Channel page customization
  • ChannelListConfig - Channel list customization
  • UsersListConfig - Users list customization
  • AuthPageConfig - Auth pages customization

Support

For issues and feature requests, visit GitHub Issues

License

MIT License - see LICENSE file for details

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Libraries

supra_stream
A plug-and-play Flutter SDK for integrating Stream Chat with Supabase.