gameball_sdk 3.1.1
gameball_sdk: ^3.1.1 copied to clipboard
Gameball Integration SDK allowing direct communication with multiple Gameball services like Customer creation, sending Events, and showing Gameball Profile
Gameball Flutter SDK #
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.1.1
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';
// Authenticated mode
final profileRequest = ShowProfileRequestBuilder()
.customerId("unique_customer_id")
.showCloseButton(true)
.closeButtonColor("#FF0000")
.build();
gameballApp.showProfile(context, profileRequest);
Guest Mode (v3.1.1+)
Display the profile widget without customer authentication:
// Guest mode - no customer ID required
final guestRequest = ShowProfileRequestBuilder()
.showCloseButton(true)
.closeButtonColor("#4CAF50")
.build();
gameballApp.showProfile(context, guestRequest);
API Methods #
The SDK provides the following public methods:
init(config)- Initialize the SDK with GameballConfiginitializeCustomer(request, callback, {sessionToken})- Register/initialize customer with builder patternsendEvent(event, callback, {sessionToken})- Track events with Event buildershowProfile(context, request, {sessionToken})- Show profile widget with ShowProfileRequest
Session Token Per-Request Override #
All SDK methods (initializeCustomer, sendEvent, showProfile) support an optional sessionToken parameter that allows you to override or nullify the global sessionToken on a per-request basis:
Behavior:
- If provided: The provided sessionToken overrides the global sessionToken set in
init()for that specific request - If not provided (null): Nullifies the global sessionToken for that specific request
- If omitted entirely: Uses the global sessionToken from
init()
Example:
// Set global sessionToken via init
final config = GameballConfigBuilder()
.apiKey("your_api_key")
.lang("en")
.sessionToken("global-token")
.build();
gameballApp.init(config);
// Use global sessionToken (from init)
await gameballApp.initializeCustomer(request, callback);
// Override with a different sessionToken for this request only
await gameballApp.initializeCustomer(request, callback, sessionToken: "specific-token");
// Nullify sessionToken for this request only
await gameballApp.initializeCustomer(request, callback, sessionToken: null);
// The next request will use whatever sessionToken was last set
await gameballApp.sendEvent(event, callback); // Uses "specific-token" from previous override
Important Notes:
- Each method call updates the global
_sessionTokenvalue. Subsequent calls will use the most recently set value unless explicitly overridden again. - The
sessionTokenparameter must be explicitly passed to every method call where you want to use a specific token. If you want to use the same custom token across multiple calls, you must pass it to each call individually or set it globally viainit().
β οΈ 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.
| Parameter | Type | Required | Description |
|---|---|---|---|
apiKey |
String | β | Your Gameball API key |
lang |
String | β | Language code (e.g., "en", "ar") |
platform |
String | β | Platform identifier |
shop |
String | β | Shop identifier |
sessionToken |
String | β | Session Token for secure authentication (enables automatic v4.1 endpoint routing) |
apiPrefix |
String | β | Custom API prefix |
Validation Rules:
apiKeycannot be null or emptylangcannot be null or empty
Builder Methods:
apiKey(String apiKey)- Sets the API keylang(String lang)- Sets the languageplatform(String platform)- Sets the platform identifiershop(String shop)- Sets the shop identifiersessionToken(String sessionToken)- Sets Session Token for secure authenticationapiPrefix(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.
| Parameter | Type | Required | Description |
|---|---|---|---|
customerId |
String | β | Unique customer identifier |
deviceToken |
String | β | Push notification token |
customerAttributes |
CustomerAttributes | β | Additional customer data |
referralCode |
String | β | Referral code for attribution |
email |
String | β | Customer email address |
mobile |
String | β | Customer mobile number |
isGuest |
bool | β | Guest status (defaults to false) |
pushProvider |
PushProvider | β | Push notification provider (Firebase/Huawei) |
Validation Rules:
customerIdcannot be null or empty- If
pushProvideris set,deviceTokenmust also be provided - If
deviceTokenis provided,pushProvidermust be specified emailmust be valid email format if providedmobilemust be valid phone number if provided
Builder Methods:
customerId(String customerId)- Sets the unique customer identifierdeviceToken(String deviceToken)- Sets the push notification tokencustomerAttributes(CustomerAttributes attributes)- Sets customer attributesreferralCode(String referralCode)- Sets referral codeemail(String email)- Sets customer emailmobile(String mobile)- Sets customer mobile numberisGuest(bool isGuest)- Sets guest statuspushProvider(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.
| Parameter | Type | Required | Description |
|---|---|---|---|
displayName |
String | β | Customer display name |
firstName |
String | β | Customer first name |
lastName |
String | β | Customer last name |
email |
String | β | Customer email |
gender |
String | β | Customer gender |
mobile |
String | β | Customer mobile number |
dateOfBirth |
String | β | Date of birth (YYYY-MM-DD format) |
joinDate |
String | β | Join date (YYYY-MM-DD format) |
preferredLanguage |
String | β | Preferred language (2-letter ISO code) |
customAttributes |
Map<String, String> | β | Custom key-value pairs |
additionalAttributes |
Map<String, String> | β | Additional flexible attributes |
channel |
String | π | Channel identifier (automatically set to "mobile") |
Validation Rules:
preferredLanguagemust be 2-letter ISO language code if providedemailmust be valid email format if provideddateOfBirthandjoinDateshould be in YYYY-MM-DD formatchannelis automatically set to "mobile" and cannot be modified
Builder Methods:
displayName(String displayName)- Sets display namefirstName(String firstName)- Sets first namelastName(String lastName)- Sets last nameemail(String email)- Sets email addressgender(String gender)- Sets gendermobile(String mobile)- Sets mobile numberdateOfBirth(String dateOfBirth)- Sets date of birthjoinDate(String joinDate)- Sets join datepreferredLanguage(String language)- Sets preferred languageaddCustomAttribute(String key, String value)- Adds custom attributecustomAttributes(Map<String, String> attributes)- Sets all custom attributesaddAdditionalAttribute(String key, String value)- Adds additional attributeadditionalAttributes(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.
| Parameter | Type | Required | Description |
|---|---|---|---|
customerId |
String | β | Customer identifier |
events |
Map<String, Map<String, Object>> | β | Event data with metadata |
email |
String | β | Customer email |
mobile |
String | β | Customer mobile number |
Validation Rules:
customerIdcannot 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 identifieremail(String email)- Sets customer emailmobile(String mobile)- Sets customer mobile numbereventName(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.
| Parameter | Type | Required | Description |
|---|---|---|---|
customerId |
String | β | Customer identifier |
openDetail |
String | β | Specific detail to open in the profile |
hideNavigation |
bool | β | Hide navigation elements |
showCloseButton |
bool | β | Show close button (defaults to true) |
closeButtonColor |
String | β | Close button color (hex format like "#FF0000") |
widgetUrlPrefix |
String | β | Custom widget URL prefix |
Validation Rules:
customerIdcannot be null or emptycloseButtonColormust be in hex format (#RRGGBB) if provided
Builder Methods:
customerId(String customerId)- Sets the customer identifieropenDetail(String openDetail)- Sets specific detail to openhideNavigation(bool hideNavigation)- Sets navigation visibilityshowCloseButton(bool showCloseButton)- Sets close button visibilitycloseButtonColor(String closeButtonColor)- Sets close button colorwidgetUrlPrefix(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 #
- π Changelog - Version history and changes
- π Migration Guide - v2.x to v3.0.0 upgrade instructions
- π Release Notes - Latest release details
Support #
- π§ Email: support@gameball.co
- π Documentation: https://developer.gameball.co/
- π Issues: GitHub Issues
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.