CoBuy SDK for Flutter

pub package License: MIT

CoBuy Flutter SDK enables group-based purchasing where multiple users can join a group to buy products together. Once the required number of members joins, the group is completed and users receive discounted pricing benefits.

๐ŸŒŸ Features

  • Group Purchasing: Enable users to form or join buying groups for products
  • Real-time Updates: WebSocket integration for live group status updates
  • Reward System: Display discounts and savings when groups are fulfilled
  • Session Management: Automatic session creation and persistence
  • Customizable UI: Configurable colors and fonts to match your brand
  • BLoC Architecture: Built with flutter_bloc for robust state management
  • Easy Integration: Simple API with minimal setup required

๐Ÿ“‹ Requirements

  • Flutter SDK: >=3.3.0
  • Dart SDK: ^3.9.2
  • iOS: 11.0+
  • Android: API level 21+

๐Ÿ“ฆ Installation

Add this to your package's pubspec.yaml file:

dependencies:
  cobuy_sdk: ^2.0.0

Then run:

flutter pub get

๐Ÿš€ Quick Start

1. Initialize the SDK

Initialize the SDK in your app's main() function with your merchant key:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize CoBuy SDK with your merchant key
  await CobuySdk.initialize(merchantKey: 'your_merchant_key_here');
  
  runApp(const MyApp());
}

2. Configure Navigator Key

Set the SDK's navigator key in your MaterialApp to enable dialog navigation:

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Your App',
      navigatorKey: CobuySdk.navigatorKey, // Required for SDK navigation
      home: const HomePage(),
    );
  }
}

3. Open Group Dialog

Call openGroupDialog when a user wants to join or create a group for a product:

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

void openCoBuyGroup(BuildContext context) async {
  await CobuySdk.openGroupDialog(
    context: context,
    productId: 'product_123',
    groupId: 'group_456',
    productName: 'Premium Headphones',
    primaryColor: Colors.blue,        // Optional: Custom brand color
    fontFamily: AppFonts.roboto,      // Optional: Custom font
  );
}

4. Cleanup on App Disposal

Dispose of the SDK resources when your app closes:

class _MyAppState extends State<MyApp> {
  @override
  void dispose() {
    CobuySdk.dispose(); // Clean up SDK resources
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: CobuySdk.navigatorKey,
      home: const HomePage(),
    );
  }
}

๐Ÿ“– Core API Reference

CobuySdk

The main entry point for the SDK.

Methods

initialize({required String merchantKey})

Initializes the SDK with your merchant credentials. Must be called before using any other SDK features.

Parameters:

  • merchantKey (String, required): Your unique merchant identifier

Example:

await CobuySdk.initialize(merchantKey: 'cobuy_merchant_abc123');
openGroupDialog({...})

Opens the group purchasing dialog for a specific product.

Parameters:

  • context (BuildContext?, optional): Widget build context. If null, uses the navigator key context
  • productId (String, required): Unique identifier for the product
  • groupId (String, required): Unique identifier for the group
  • productName (String, required): Display name of the product
  • primaryColor (Color?, optional): Custom theme color for the dialog
  • fontFamily (AppFonts?, optional): Custom font family from SDK fonts

Example:

await CobuySdk.openGroupDialog(
  context: context,
  productId: 'shoe_001',
  groupId: 'group_789',
  productName: 'Running Shoes',
  primaryColor: Colors.green,
  fontFamily: AppFonts.poppins,
);
dispose()

Cleans up SDK resources including WebSocket connections. Call this when your app is disposed.

CobuySdk.dispose();
destroy()

Completely destroys the SDK session including clearing stored session data. Use this for logout scenarios.

CobuySdk.destroy();

A global navigator key provided by the SDK for navigation without context.

GlobalKey<NavigatorState> key = CobuySdk.navigatorKey;

๐ŸŽจ Customization

Available Fonts

The SDK provides several font options via the AppFonts enum:

  • AppFonts.roboto
  • AppFonts.openSans
  • AppFonts.lato
  • AppFonts.montserrat
  • AppFonts.poppins
  • AppFonts.raleway
  • AppFonts.ubuntu
  • AppFonts.nunito
  • AppFonts.arimo (default)

Exported Widgets

The SDK exports reusable widgets for custom integrations:

import 'package:cobuy_sdk/src/cobuysdk.dart';

// Available exports:
// - AppFonts enum
// - CoBuyProgressWidget
// - CoBuyTextWidget

๐Ÿ—๏ธ Architecture

The SDK follows clean architecture principles with BLoC pattern:

lib/
โ”œโ”€โ”€ cobuy_sdk.dart              # Main SDK entry point
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ api/                    # API layer
โ”‚   โ”‚   โ”œโ”€โ”€ api_endpoints.dart  # API endpoint configurations
โ”‚   โ”‚   โ”œโ”€โ”€ session_storage.dart# Session persistence
โ”‚   โ”‚   โ””โ”€โ”€ socket_service.dart # WebSocket real-time updates
โ”‚   โ”œโ”€โ”€ bloc/                   # Business logic
โ”‚   โ”‚   โ”œโ”€โ”€ group_bloc.dart     # Group state management
โ”‚   โ”‚   โ”œโ”€โ”€ group_event.dart    # Group events
โ”‚   โ”‚   โ””โ”€โ”€ group_state.dart    # Group states
โ”‚   โ”œโ”€โ”€ core/                   # Core initialization
โ”‚   โ”‚   โ””โ”€โ”€ cobuy_initializer.dart
โ”‚   โ”œโ”€โ”€ init_bloc/              # SDK initialization logic
โ”‚   โ”œโ”€โ”€ model/                  # Data models
โ”‚   โ”‚   โ”œโ”€โ”€ get_group_join_data.dart
โ”‚   โ”‚   โ”œโ”€โ”€ get_group_list_data.dart
โ”‚   โ”‚   โ”œโ”€โ”€ get_reward_group_data.dart
โ”‚   โ”‚   โ”œโ”€โ”€ group_member.dart
โ”‚   โ”‚   โ””โ”€โ”€ session_response.dart
โ”‚   โ”œโ”€โ”€ repository/             # Data layer
โ”‚   โ”‚   โ””โ”€โ”€ cobuy_repository.dart
โ”‚   โ”œโ”€โ”€ utils/                  # Utility functions
โ”‚   โ””โ”€โ”€ widget/                 # Reusable UI widgets
โ”‚       โ”œโ”€โ”€ count_down_timer.dart
โ”‚       โ”œโ”€โ”€ group_list_route.dart
โ”‚       โ”œโ”€โ”€ progress_bar_widget.dart
โ”‚       โ””โ”€โ”€ text_widget.dart

๐Ÿ”„ State Management

The SDK uses flutter_bloc for state management. Key states include:

GroupBloc States

  • GroupInitial: Initial state
  • GroupLoading: Loading group data
  • GroupJoinedState: User successfully joined a group
  • GetRewardGroupDataState: Reward/discount data loaded
  • GetPrimaryGroupState: Primary group data loaded
  • GetGroupListState: Available groups loaded
  • GroupError: Error occurred

GroupBloc Events

  • JoinGroupEvent: Join or create a group
  • GetRewardGroupEvent: Fetch reward information
  • GetPrimaryGroupEvent: Fetch the primary group for a product
  • GetGroupListEvent: Fetch all available groups

๐ŸŒ Real-time Updates

The SDK includes WebSocket support for real-time group updates:

  • Member joined notifications
  • Group fulfilled events
  • Live member count updates

The socket connection is managed automatically during SDK initialization.

๐Ÿ“ฑ Example Integration

See the complete example in the /example folder:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await CobuySdk.initialize(merchantKey: 'cobuy_test_ABC123XYZ890');
  runApp(const MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void dispose() {
    CobuySdk.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      navigatorKey: CobuySdk.navigatorKey,
      home: const ProductListScreen(),
    );
  }
}

๐Ÿงช Testing

The SDK includes test coverage for:

  • BLoC unit tests
  • Repository tests
  • Widget tests

Run tests with:

flutter test

๐Ÿ”’ Session Management

The SDK automatically manages user sessions:

  1. Session Creation: Automatically creates a session on first initialization
  2. Session Persistence: Sessions are stored locally using shared_preferences
  3. Session Reuse: Existing sessions are reused across app restarts
  4. Session Cleanup: Use CobuySdk.destroy() to clear session data

๐Ÿ“Š Dependencies

Key dependencies used by the SDK:

  • flutter_bloc: ^9.0.0 - State management
  • socket_io_client: ^3.1.3 - Real-time WebSocket communication
  • http: ^1.6.0 - HTTP networking
  • shared_preferences: ^2.2.1 - Local session storage
  • flutter_svg: ^2.2.3 - SVG asset rendering
  • google_fonts: ^6.3.3 - Custom typography
  • shimmer: ^3.0.0 - Loading animations
  • connectivity_plus: ^7.0.0 - Network state monitoring

๐Ÿ› Known Issues

For a detailed list of known issues and recommended fixes, see ISSUE_REPORT.md.

Critical items being addressed:

  • DateTime parsing guards for invalid API dates
  • BLoC disposal in dialog and widget lifecycles
  • Socket listener cleanup on widget disposal
  • Zero-division guards in progress calculations

๐Ÿค Contributing

Contributions are welcome! Please follow these guidelines:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ“ž Support

For questions or support, please:

  1. Check the example app for implementation guidance
  2. Review the ISSUE_REPORT.md for known issues
  3. Open an issue on GitHub

๐ŸŽฏ Roadmap

  • Enhanced error handling and recovery
  • Improved offline support
  • Additional customization options
  • Performance optimizations
  • Comprehensive integration tests
  • Analytics and tracking support

Made with โค๏ธ by the CoBuy Team