gameball_sdk 3.0.0

SDKflutter
Platformandroidios

Gameball Integration SDK allowing direct communication with multiple Gameball services like Customer creation, sending Events, and showing Gameball Profile

Gameball Flutter SDK

Version License Flutter Dart

Gameball Flutter SDK allows you to integrate customer engagement and loyalty features into your Flutter applications with modern builder patterns and immutable request models.

Features

  • 🎯 Customer Management - Initialize and manage customer profiles with builder pattern
  • 📊 Event Tracking - Track user actions and behaviors with flexible metadata
  • 🎁 Profile Widget - Display customer loyalty information in customizable UI
  • 🔧 Modern Architecture - Built with Flutter best practices and null safety
  • 🛡️ Type Safety - Compile-time validation with Dart's type system
  • Async/Await Ready - Modern async architecture with proper error handling

Requirements

  • Minimum Flutter Version: 1.17.0
  • Dart: 3.4.4+
  • Android: API level 21+
  • iOS: 12.0+

Note: While the SDK supports Flutter 1.17.0+, we recommend using Flutter 3.0+ for the best development experience with modern features like null safety and enhanced tooling.

Installation

pubspec.yaml

dependencies:
  gameball_sdk: ^3.0.0

Flutter CLI

flutter pub add gameball_sdk

Quick Start

1. Initialize the SDK

import 'package:gameball_sdk/gameball_sdk.dart';
import 'package:gameball_sdk/models/requests/gameball_config.dart';

final gameballApp = GameballApp.getInstance();

final config = GameballConfigBuilder()
    .apiKey("your_api_key")
    .lang("en")
    .platform("your_platform")
    .shop("your_shop")
    .build();

gameballApp.init(config);

2. Initialize Customer

import 'package:gameball_sdk/models/requests/initialize_customer_request.dart';
import 'package:gameball_sdk/models/requests/customer_attributes.dart';

final request = InitializeCustomerRequestBuilder()
    .customerId("unique_customer_id")
    .email("customer@example.com")
    .mobile("1234567890")
    .customerAttributes(
        CustomerAttributesBuilder()
            .displayName("John Doe")
            .firstName("John")
            .lastName("Doe")
            .addCustomAttribute("city", "New York")
            .build()
    )
    .build();

await gameballApp.initializeCustomer(request, (response, error) {
    if (error == null) {
        print('Customer initialized successfully');
    } else {
        print('Error: ${error.toString()}');
    }
});

3. Track Events

import 'package:gameball_sdk/models/requests/event.dart';

final event = EventBuilder()
    .customerId("unique_customer_id")
    .eventName("purchase")
    .eventMetaData("amount", "100.00")
    .eventMetaData("currency", "USD")
    .build();

gameballApp.sendEvent(event, (success, error) {
    if (success == true) {
        print('Event sent successfully');
    } else {
        print('Error sending event: ${error?.toString()}');
    }
});

4. Show Profile Widget

import 'package:gameball_sdk/models/requests/show_profile_request.dart';

final profileRequest = ShowProfileRequestBuilder()
    .customerId("unique_customer_id")
    .showCloseButton(true)
    .closeButtonColor("#FF0000")
    .build();

gameballApp.showProfile(context, profileRequest);

API Methods

The SDK provides the following public methods:

  • getInstance() - Get the singleton instance of GameballApp
  • init(config) - Initialize the SDK with GameballConfig
  • initializeCustomer(request, callback) - Register/initialize customer with builder pattern
  • sendEvent(event, callback) - Track events with Event builder
  • showProfile(context, request) - Show profile widget with ShowProfileRequest

⚠️ Migration from v2.x

Version 3.0.0 contains breaking changes. See Migration Guide for detailed upgrade instructions.

Key Changes in v3.0.0:

  • All request models now use builder pattern
  • Immutable request objects with compile-time validation
  • Enhanced API key validation
  • Simplified architecture with cleaner data flow

Configuration Options

GameballConfig

Configuration object for initializing the Gameball SDK.

ParameterTypeRequiredDescription
apiKeyStringYour Gameball API key
langStringLanguage code (e.g., "en", "ar")
platformStringPlatform identifier
shopStringShop identifier
apiPrefixStringCustom API prefix

Validation Rules:

  • apiKey cannot be null or empty
  • lang cannot be null or empty

Builder Methods:

  • apiKey(String apiKey) - Sets the API key
  • lang(String lang) - Sets the language
  • platform(String platform) - Sets the platform identifier
  • shop(String shop) - Sets the shop identifier
  • apiPrefix(String apiPrefix) - Sets custom API prefix

Example:

import 'package:gameball_sdk/models/requests/gameball_config.dart';

final config = GameballConfigBuilder()
    .apiKey("your_api_key_here")
    .lang("en")
    .platform("mobile")
    .shop("your_shop")
    .build();

InitializeCustomerRequest

Request object for initializing/registering customers with the Gameball platform.

ParameterTypeRequiredDescription
customerIdStringUnique customer identifier
deviceTokenStringPush notification token
customerAttributesCustomerAttributesAdditional customer data
referralCodeStringReferral code for attribution
emailStringCustomer email address
mobileStringCustomer mobile number
isGuestboolGuest status (defaults to false)
pushProviderPushProviderPush notification provider (Firebase/Huawei)

Validation Rules:

  • customerId cannot be null or empty
  • If pushProvider is set, deviceToken must also be provided
  • If deviceToken is provided, pushProvider must be specified
  • email must be valid email format if provided
  • mobile must be valid phone number if provided

Builder Methods:

  • customerId(String customerId) - Sets the unique customer identifier
  • deviceToken(String deviceToken) - Sets the push notification token
  • customerAttributes(CustomerAttributes attributes) - Sets customer attributes
  • referralCode(String referralCode) - Sets referral code
  • email(String email) - Sets customer email
  • mobile(String mobile) - Sets customer mobile number
  • isGuest(bool isGuest) - Sets guest status
  • pushProvider(PushProvider provider) - Sets push provider (Firebase/Huawei)

Example:

import 'package:gameball_sdk/models/requests/initialize_customer_request.dart';
import 'package:gameball_sdk/models/enums/push_provider.dart';

final request = InitializeCustomerRequestBuilder()
    .customerId("customer_123")
    .email("john@example.com")
    .mobile("1234567890")
    .deviceToken("firebase_token")
    .pushProvider(PushProvider.Firebase)
    .referralCode("REF123")
    .isGuest(false)
    .customerAttributes(attributes)
    .build();

CustomerAttributes

Additional customer information for enriching customer profiles and personalization.

ParameterTypeRequiredDescription
displayNameStringCustomer display name
firstNameStringCustomer first name
lastNameStringCustomer last name
emailStringCustomer email
genderStringCustomer gender
mobileStringCustomer mobile number
dateOfBirthStringDate of birth (YYYY-MM-DD format)
joinDateStringJoin date (YYYY-MM-DD format)
preferredLanguageStringPreferred language (2-letter ISO code)
customAttributesMap<String, String>Custom key-value pairs
additionalAttributesMap<String, String>Additional flexible attributes
channelString🔒Channel identifier (automatically set to "mobile")

Validation Rules:

  • preferredLanguage must be 2-letter ISO language code if provided
  • email must be valid email format if provided
  • dateOfBirth and joinDate should be in YYYY-MM-DD format
  • channel is automatically set to "mobile" and cannot be modified

Builder Methods:

  • displayName(String displayName) - Sets display name
  • firstName(String firstName) - Sets first name
  • lastName(String lastName) - Sets last name
  • email(String email) - Sets email address
  • gender(String gender) - Sets gender
  • mobile(String mobile) - Sets mobile number
  • dateOfBirth(String dateOfBirth) - Sets date of birth
  • joinDate(String joinDate) - Sets join date
  • preferredLanguage(String language) - Sets preferred language
  • addCustomAttribute(String key, String value) - Adds custom attribute
  • customAttributes(Map<String, String> attributes) - Sets all custom attributes
  • addAdditionalAttribute(String key, String value) - Adds additional attribute
  • additionalAttributes(Map<String, String> attributes) - Sets all additional attributes

Example:

import 'package:gameball_sdk/models/requests/customer_attributes.dart';

final attributes = CustomerAttributesBuilder()
    .displayName("John Doe")
    .firstName("John")
    .lastName("Doe")
    .email("john@example.com")
    .mobile("1234567890")
    .gender("male")
    .dateOfBirth("1990-01-15")
    .preferredLanguage("en")
    .addCustomAttribute("tier", "premium")
    .addCustomAttribute("city", "New York")
    .addAdditionalAttribute("segment", "vip")
    .addAdditionalAttribute("source", "mobile_app")
    .build();

Event

Event objects for tracking customer actions and behaviors for analytics and campaign triggers.

ParameterTypeRequiredDescription
customerIdStringCustomer identifier
eventsMap<String, Map<String, Object>>Event data with metadata
emailStringCustomer email
mobileStringCustomer mobile number

Validation Rules:

  • customerId cannot be null or empty
  • At least one event must be specified
  • Event names should be meaningful and descriptive
  • Event metadata values can be String, Number, or Boolean

Builder Methods:

  • customerId(String customerId) - Sets the customer identifier
  • email(String email) - Sets customer email
  • mobile(String mobile) - Sets customer mobile number
  • eventName(String eventName) - Sets current event name (must be called before adding metadata)
  • eventMetaData(String key, Object value) - Adds metadata to current event

Example:

import 'package:gameball_sdk/models/requests/event.dart';

final event = EventBuilder()
    .customerId("customer_123")
    .email("john@example.com")
    .mobile("1234567890")
    .eventName("purchase")
    .eventMetaData("amount", 99.99)
    .eventMetaData("currency", "USD")
    .eventMetaData("product_id", "prod_123")
    .eventMetaData("category", "electronics")
    .build();

// Multiple events example
final multipleEvents = EventBuilder()
    .customerId("customer_123")
    .eventName("page_view")
    .eventMetaData("page", "product_detail")
    .eventMetaData("product_id", "prod_123")
    .eventName("add_to_cart")
    .eventMetaData("product_id", "prod_123")
    .eventMetaData("quantity", 1)
    .build();

ShowProfileRequest

Request object for displaying the Gameball customer profile widget with customization options.

ParameterTypeRequiredDescription
customerIdStringCustomer identifier
openDetailStringSpecific detail to open in the profile
hideNavigationboolHide navigation elements
showCloseButtonboolShow close button (defaults to true)
closeButtonColorStringClose button color (hex format like "#FF0000")
widgetUrlPrefixStringCustom widget URL prefix

Validation Rules:

  • customerId cannot be null or empty
  • closeButtonColor must be in hex format (#RRGGBB) if provided

Builder Methods:

  • customerId(String customerId) - Sets the customer identifier
  • openDetail(String openDetail) - Sets specific detail to open
  • hideNavigation(bool hideNavigation) - Sets navigation visibility
  • showCloseButton(bool showCloseButton) - Sets close button visibility
  • closeButtonColor(String closeButtonColor) - Sets close button color
  • widgetUrlPrefix(String widgetUrlPrefix) - Sets custom widget URL prefix

Example:

import 'package:gameball_sdk/models/requests/show_profile_request.dart';

final profileRequest = ShowProfileRequestBuilder()
    .customerId("customer_123")
    .openDetail("rewards")
    .hideNavigation(false)
    .showCloseButton(true)
    .closeButtonColor("#FF6B6B")
    .widgetUrlPrefix("https://custom.example.com/widget")
    .build();

gameballApp.showProfile(context, profileRequest);

Advanced Usage

Customer Attributes with Builder

import 'package:gameball_sdk/models/requests/customer_attributes.dart';

final attributes = CustomerAttributesBuilder()
    .displayName("John Doe")
    .email("john@example.com")
    .mobile("1234567890")
    .preferredLanguage("en")
    .addCustomAttribute("tier", "premium")
    .addCustomAttribute("city", "New York")
    .addAdditionalAttribute("segment", "vip")
    .build();

Push Notifications

import 'package:gameball_sdk/models/requests/initialize_customer_request.dart';
import 'package:gameball_sdk/models/enums/push_provider.dart';

// Firebase FCM
final request = InitializeCustomerRequestBuilder()
    .customerId("customer_id")
    .deviceToken("fcm_token")
    .pushProvider(PushProvider.Firebase)
    .build();

// Huawei Push Kit
final request = InitializeCustomerRequestBuilder()
    .customerId("customer_id")
    .deviceToken("hms_token")
    .pushProvider(PushProvider.Huawei)
    .build();

Error Handling

try {
    await gameballApp.initializeCustomer(request, (response, error) {
        if (error != null) {
            // Handle API errors
            print('API Error: ${error.toString()}');
        } else {
            // Handle success
            print('Customer initialized: ${response?.toString()}');
        }
    });
} catch (e) {
    // Handle SDK exceptions
    print('SDK Exception: ${e.toString()}');
}

Troubleshooting

Common Issues

1. API Key Not Initialized

Error: API key is not initialized. Call init() first

Solution: Ensure you call gameballApp.init(config) before any other SDK methods.

2. Invalid Customer ID

Error: Customer ID cannot be empty

Solution: Provide a valid, non-empty customer ID in your requests.

3. Push Provider Validation

Error: Device token is required when push provider is set

Solution: When setting a push provider, ensure you also provide a valid device token.

Debug Logging

Enable Flutter's debug logging to see detailed SDK operation logs:

flutter run --verbose

Documentation

Support

License

MIT License

Copyright (c) 2024 Gameball

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.