Back to Documentation

Flutter SDK Examples

Real-world examples showing how to use the OddSockets Flutter SDK in production applications across all platforms

Basic Usage
Available
Simple example showing how to connect, subscribe to a channel, and publish messages using the core Flutter SDK functionality.
import 'package:oddsockets_flutter/oddsockets_flutter.dart';

final client = OddSocketsClient(
  OddSocketsConfig.defaultConfig('ak_live_1234567890abcdef'),
);

final channel = client.channel('my-channel');

// Subscribe to messages
await channel.subscribe((message) {
  print('Received: ${message.data}');
});

// Publish a message
await channel.publish('Hello, Flutter!');
StreamBuilder Integration
Available
Flutter-native example showing how to integrate OddSockets with StreamBuilder for reactive UI updates.
class ChatWidget extends StatefulWidget {
  @override
  _ChatWidgetState createState() => _ChatWidgetState();
}

class _ChatWidgetState extends State<ChatWidget> {
  late OddSocketsClient client;
  late OddSocketsChannel channel;

  @override
  void initState() {
    super.initState();
    client = OddSocketsClient(
      OddSocketsConfig.defaultConfig('ak_live_1234567890abcdef'),
    );
    channel = client.channel('chat-room');
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<Message>(
      stream: channel.messageStream,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Text('Latest: ${snapshot.data!.data}');
        }
        return Text('Waiting for messages...');
      },
    );
  }
}
BLoC Integration
Available
Advanced example showing how to integrate OddSockets with flutter_bloc for state management in complex applications.
class ChatBloc extends Bloc<ChatEvent, ChatState> {
  final OddSocketsClient _client;
  late final OddSocketsChannel _channel;
  late StreamSubscription _messageSubscription;

  ChatBloc(this._client) : super(ChatInitial()) {
    _channel = _client.channel('chat-room');
    
    on<ChatStarted>(_onChatStarted);
    on<MessageReceived>(_onMessageReceived);
    on<MessageSent>(_onMessageSent);
  }

  Future<void> _onChatStarted(ChatStarted event, Emitter<ChatState> emit) async {
    await _channel.subscribe((message) {
      add(MessageReceived(message));
    });
    
    emit(ChatConnected([]));
  }
}
Cross-Platform Chat App
Available
Complete chat application that works on iOS, Android, Web, Windows, macOS, and Linux with platform-specific optimizations.
class CrossPlatformChatApp extends StatefulWidget {
  @override
  _CrossPlatformChatAppState createState() => _CrossPlatformChatAppState();
}

class _CrossPlatformChatAppState extends State<CrossPlatformChatApp> {
  late OddSocketsClient client;
  late OddSocketsChannel channel;

  @override
  void initState() {
    super.initState();
    
    // Platform-specific configuration
    final config = _getPlatformConfig();
    client = OddSocketsClient(config);
    channel = client.channel('cross-platform-chat');
  }

  OddSocketsConfig _getPlatformConfig() {
    if (Platform.isIOS || Platform.isAndroid) {
      return OddSocketsConfig.builder('ak_live_1234567890abcdef')
          .mobile()
          .build();
    } else if (kIsWeb) {
      return OddSocketsConfig.builder('ak_live_1234567890abcdef')
          .web()
          .build();
    } else {
      return OddSocketsConfig.builder('ak_live_1234567890abcdef')
          .desktop()
          .build();
    }
  }
}
Real-time Gaming
Available
Multiplayer game example showing low-latency real-time communication for gaming applications with presence tracking.
class GameRoom extends StatefulWidget {
  final String roomId;
  
  const GameRoom({Key? key, required this.roomId}) : super(key: key);

  @override
  _GameRoomState createState() => _GameRoomState();
}

class _GameRoomState extends State<GameRoom> {
  late OddSocketsClient client;
  late OddSocketsChannel gameChannel;
  List<Player> players = [];

  @override
  void initState() {
    super.initState();
    
    // Gaming-optimized configuration
    final config = OddSocketsConfig.builder('ak_live_1234567890abcdef')
        .heartbeatInterval(Duration(seconds: 10)) // Faster heartbeat for gaming
        .reconnectAttempts(10)
        .build();
    
    client = OddSocketsClient(config);
    gameChannel = client.channel('game-${widget.roomId}');
    
    _setupGameChannel();
  }

  void _setupGameChannel() async {
    await gameChannel.subscribe((message) {
      _handleGameMessage(message);
    }, SubscribeOptions(
      enablePresence: true, // Track players joining/leaving
      retainHistory: false, // Don't retain game messages
    ));
  }
}
IoT Dashboard
Available
IoT monitoring dashboard showing real-time sensor data visualization with Flutter charts and OddSockets integration.
class IoTDashboard extends StatefulWidget {
  @override
  _IoTDashboardState createState() => _IoTDashboardState();
}

class _IoTDashboardState extends State<IoTDashboard> {
  late OddSocketsClient client;
  late OddSocketsChannel sensorChannel;
  List<SensorReading> readings = [];

  @override
  void initState() {
    super.initState();
    
    client = OddSocketsClient(
      OddSocketsConfig.defaultConfig('ak_live_1234567890abcdef'),
    );
    sensorChannel = client.channel('iot-sensors');
    
    _setupSensorChannel();
  }

  void _setupSensorChannel() async {
    await sensorChannel.subscribe((message) {
      final reading = SensorReading.fromJson(message.data);
      setState(() {
        readings.add(reading);
        // Keep only last 100 readings for performance
        if (readings.length > 100) {
          readings.removeAt(0);
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('IoT Dashboard')),
      body: Column(
        children: [
          // Real-time chart
          Expanded(
            child: LineChart(
              LineChartData(
                lineBarsData: [
                  LineChartBarData(
                    spots: readings.map((r) => 
                      FlSpot(r.timestamp.millisecondsSinceEpoch.toDouble(), r.value)
                    ).toList(),
                  ),
                ],
              ),
            ),
          ),
          // Current readings
          StreamBuilder<Message>(
            stream: sensorChannel.messageStream,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                final reading = SensorReading.fromJson(snapshot.data!.data);
                return Text('Current: ${reading.value}°C');
              }
              return Text('Waiting for data...');
            },
          ),
        ],
      ),
    );
  }
}