cobuy_sdk 3.0.0
cobuy_sdk: ^3.0.0 copied to clipboard
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 dis [...]
CoBuy SDK for Flutter #
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 contextproductId(String, required): Unique identifier for the productgroupId(String, required): Unique identifier for the groupproductName(String, required): Display name of the productprimaryColor(Color?, optional): Custom theme color for the dialogfontFamily(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();
navigatorKey
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.robotoAppFonts.openSansAppFonts.latoAppFonts.montserratAppFonts.poppinsAppFonts.ralewayAppFonts.ubuntuAppFonts.nunitoAppFonts.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 stateGroupLoading: Loading group dataGroupJoinedState: User successfully joined a groupGetRewardGroupDataState: Reward/discount data loadedGetPrimaryGroupState: Primary group data loadedGetGroupListState: Available groups loadedGroupError: Error occurred
GroupBloc Events #
JoinGroupEvent: Join or create a groupGetRewardGroupEvent: Fetch reward informationGetPrimaryGroupEvent: Fetch the primary group for a productGetGroupListEvent: 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:
- Session Creation: Automatically creates a session on first initialization
- Session Persistence: Sessions are stored locally using shared_preferences
- Session Reuse: Existing sessions are reused across app restarts
- Session Cleanup: Use
CobuySdk.destroy()to clear session data
π Dependencies #
Key dependencies used by the SDK:
flutter_bloc: ^9.0.0 - State managementsocket_io_client: ^3.1.3 - Real-time WebSocket communicationhttp: ^1.6.0 - HTTP networkingshared_preferences: ^2.2.1 - Local session storageflutter_svg: ^2.2.3 - SVG asset renderinggoogle_fonts: ^6.3.3 - Custom typographyshimmer: ^3.0.0 - Loading animationsconnectivity_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:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
π License #
This project is licensed under the MIT License - see the LICENSE file for details.
π Links #
- Repository: https://github.com/Co-Buy-by-Media-North/Co-buy-flutter-sdk
- Issue Tracker: GitHub Issues
- Changelog: CHANGELOG.md
π Support #
For questions or support, please:
- Check the example app for implementation guidance
- Review the ISSUE_REPORT.md for known issues
- 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