# Initialization

{% hint style="warning" %}

#### Initialize After Media Source or MMP Initialization

Please initialize our SDK only after the media source or MMP data is initialized. This ensures that the media source data is sent correctly and prevents passing empty values.
{% endhint %}

Integrating the Tyrads offerwall functionality into your application is a straightforward process that involves a few key steps. By following these integration steps, you can seamlessly incorporate the offerwall feature, enhancing user engagement and potentially generating revenue for your application.

### 1. Initialization

Initialization should occur as early as possible in your app's lifecycle (e.g., in `main()` or your initial landing page).

> \[!IMPORTANT] **Mandatory Navigator Key**: You must now provide a `GlobalKey<NavigatorState>` during initialization. This allows the SDK to manage overlays and navigation without requiring you to pass a `BuildContext` manually.

{% hint style="success" %}

### SDK Initialization best practices:

* **Initiate early:** It's advisable to initialize the SDK promptly after your app launches to ensure that all Tyr SDK functionalities are accessible when needed.
* **Initiate post-app authentication:** Re-initiate the SDK with current user details immediately after your user signs up or signs in to the app to update the `userId`.
* **Initiate periodically:** To optimize user experience, we strongly suggest invoking this method each time your app is brought to the forefront. This shouldn't impact your app's performance noticeably.
  {% endhint %}

This step initializes the Tyrads SDK within your application. You need to provide the API key and API secret obtained from the Tyrads platform. This allows your app to communicate securely with Tyrads' servers.

#### Basic Initialization

```dart
// 1. Create a GlobalKey in your main application state or global scope
final GlobalKey<NavigatorState> hostNavigatorKey = GlobalKey<NavigatorState>();

// 2. Assign it to your MaterialApp
MaterialApp(
  navigatorKey: hostNavigatorKey,
  // ... rest of your app
);

// 3. Initialize the SDK
await Tyrads.instance.init(
  navigatorKey: hostNavigatorKey, // Mandatory
  apiKey: "YOUR_API_KEY",
  apiSecret: "YOUR_API_SECRET",
);
```

#### Advanced Initialization (Personalized Rewards)

To maximize earnings and segment users, you can provide advanced user and media source information:

```dart
await Tyrads.instance.init(
  navigatorKey: hostNavigatorKey,
  apiKey: "YOUR_API_KEY",
  apiSecret: "YOUR_API_SECRET",
  encKey: "YOUR_ENCRYPTION_KEY", // Optional: Encrypts transmitted data
  userInfo: TyradsUserInfo(
    email: "user@example.com",
    userGroup: "High purchasing user",
    age: 28,
    gender: 1, // Male
  ),
  mediaSourceInfo: TyradsMediaSourceInfo(
    mediaSourceName: "Facebook",
    mediaCampaignName: "Summer2023Promo",
    mediaSourceId: "FB001",
    mediaSubSourceId: "FB001_Stories",
    incentivized: false,
    mediaAdsetName: "YoungAdults25-34",
    mediaAdsetId: "AD001",
    mediaCreativeName: "SummerSale_Video",
    mediaCreativeId: "CR001",
    sub1: "ReferralCode123",
    sub2: "OrganicInstall",
    sub3: "HighValueUser",
    sub4: "FirstTimeUser",
    sub5: "iOSDevice",
  ),
  config: TyradsConfig(
    skipInitialPages: true, // Only applied when running on Android
  ),
);
```

***

#### 1.1 Initialization Parameter Reference

{% hint style="warning" %}
To maximize the value to the user sending us more data about the user and where they came from allow us to customize the reward experience. This can be used to provide feedback of quality of users aswell as customize the earnings journey of different segments of users.&#x20;
{% endhint %}

The `init` method accepts several parameters to configure the SDK and enhance user attribution.

| Parameter         | Type                        | Required | Description                                                                                                                     |
| ----------------- | --------------------------- | :------: | ------------------------------------------------------------------------------------------------------------------------------- |
| `navigatorKey`    | `GlobalKey<NavigatorState>` |  **Yes** | The anchor for all SDK UI. Must be the same key assigned to your `MaterialApp`.                                                 |
| `apiKey`          | `String`                    |  **Yes** | Your unique publisher identifier obtained from the Tyrads Dashboard.                                                            |
| `apiSecret`       | `String`                    |  **Yes** | Your publisher secret key used for secure server communication.                                                                 |
| `encKey`          | `String`                    |    No    | **Encryption Key**: If provided, the SDK encrypts sensitive data during transmission. Recommended for high-security apps.       |
| `userInfo`        | `TyradsUserInfo`            |    No    | Metadata about the user (email, phone, user group) used for segmenting and personalizing offers.                                |
| `mediaSourceInfo` | `TyradsMediaSourceInfo`     |    No    | **Attribution Data**: Details about where the user came from (e.g., Facebook, Organic). Helps in tracking campaign performance. |
| `config`          | `TyradsConfig`              |    No    | Android Only: settings for Android behavior, such as `skipInitialPages` to bypass privacy/permission screens.                   |
| `launchMode`      | `TyradsLaunchMode`          |    No    | Internal configuration for how the offerwall container is launched.                                                             |

***

#### Detailed Objects

**TyradsUserInfo**

Used to provide context about the current user for better offer matching and demographic targeting.

* **`email`**: User's email address.
* **`phoneNumber`**: User's contact number.
* **`userGroup`**: A custom string to categorize users (e.g., "VIP", "High purchasing user").
* **`age`**: The user's age (e.g., `25`).
* **`gender`**: The user's gender represented as an integer (e.g., `1` for Male, `2` for Female).

**TyradsMediaSourceInfo**

Essential for publishers who want to track the source of their users.

* `mediaSourceName`: The platform name (e.g., "GoogleAdWords", "Facebook").
* `mediaCampaignName`: The specific marketing campaign name.
* `mediaCreativeId`: The ID of the specific ad creative the user interacted with.
* `sub1` through `sub5`: Custom slots for any additional tracking parameters you require.

[Sending Media Source Data](/getting-started/advanced-options/sending-media-source-data.md)

[Sending User Segments / User Info](/getting-started/advanced-options/sending-user-segments-user-info.md)

***

### 2. User Authentication

Logging in the user is mandatory. While providing a `userID` is optional, we **strongly recommend** using your own internal User ID to ensure progress is saved across device changes.

```dart
// userID is your internal app identifier for the user
await Tyrads.instance.loginUser(userID: "my_unique_user_123");
```

{% hint style="warning" %}
The generated user ID from the SDK is based on the device identifier (GAID/OAID/IDFA)

* If your app user resets the device identifier, your user will lose the progress data
* If the SDK can't access the device identifier, it will generate its own device identifier and store it in the app storage. If this is the case, your app user will lose the progress data when the user uninstalls the app
* **If you send us your userId within userId field from your backend we will save this and even if the user changes their device ID we will keep their progress.**&#x20;
  {% endhint %}

***

### 3. Showing the Offerwall

Once initialized and logged in, you can display the Offerwall.

> \[!NOTE] **Context Free**: You no longer need to pass a `BuildContext` to `showOffers()`. The SDK uses the global `navigatorKey` provided during initialization.

```dart
// Opens the default offers page
await Tyrads.instance.showOffers();

// Opens the offerwall with specific routing
await Tyrads.instance.showOffers(
  route: TyradsDeepRoutes.ACTIVE_OFFERS,
  // campaignID: 12345, // Required for specific campaign routes
);
```

<details>

<summary><strong>Launch Mode</strong></summary>

The Tyrads SDK provides two primary ways to display the Offerwall to your users. You can configure this globally during initialization or override it for specific calls.

#### TyradsLaunchMode Types

| Mode              | Description                                                                               |
| ----------------- | ----------------------------------------------------------------------------------------- |
| `webview`         | **(Default)** Opens the Offerwall within an internal SDK-managed WebView inside your app. |
| `externalBrowser` | Opens the Offerwall in the user's default system browser (e.g., Chrome, Safari).          |

***

#### 1. Global Configuration

Set the default launch behavior during SDK initialization:

```dart
await Tyrads.instance.init(
  navigatorKey: hostNavigatorKey,
  apiKey: "YOUR_API_KEY",
  apiSecret: "YOUR_API_SECRET",
  launchMode: TyradsLaunchMode.webview, // Global default
);
```

#### 2. Manual Override

Override the global setting when calling `showOffers`:

```dart
// Force this specific opening to use the external browser
await Tyrads.instance.showOffers(
  launchMode: TyradsLaunchMode.externalBrowser,
);
```

#### 3. Dynamic Update

You can also change the global launch mode at any time after initialization:

```dart
Tyrads.instance.setLaunchMode(TyradsLaunchMode.externalBrowser);
```

***

> \[!IMPORTANT] **Safety & Integrity**: Even when using `externalBrowser` mode, the SDK automatically performs all mandatory checks (Login, SDK Initialization, and Onboarding) before triggering the redirection. This ensures user tracking and campaign attribution remain 100% accurate.

</details>

#### Deep Link Routes

**Min SDK version required: v1.1.4**

The Tyrads SDK supports deeplinking to specific sections of the offerwall. When initializing or interacting with the SDK, you can specify a route to open a particular page. For campaign-specific routes, you'll need to provide the campaignID as well.

| Route Name                                                    | Constant                         | Description                                            |
| ------------------------------------------------------------- | -------------------------------- | ------------------------------------------------------ |
| `offers`                                                      | `TyradsDeepRoutes.OFFERS`        | Main campaigns list (Default)                          |
| `active-offers`                                               | `TyradsDeepRoutes.ACTIVE_OFFERS` | User's activated campaigns                             |
| `offers/`<mark style="color:$warning;">`[campaign-id]`</mark> | `TyradsDeepRoutes.OFFERS`        | Specific campaign details (Requires `campaignID`)      |
| `support`                                                     | `TyradsDeepRoutes.SUPPORT`       | Support tickets for a campaign (Requires `campaignID`) |

Available routes and their usage:

* `offers` - opens the Campaigns Page
* `active-offers` - opens the Activated Campaigns Page
* `offers/`<mark style="color:$warning;">`[campaign-id]`</mark> - opens the Campaign Details Page (requires campaignID)
* `support` - opens the Campaign Tickets Page (requires campaignID)

```dart
// Note: CAMPAIGNS is the default route when no specific route is provided
await Tyrads.instance.showOffers();

// Explicitly specifying the Campaigns Page
await Tyrads.instance.showOffers(route: "offers");
//or use TyradsDeepRoutes class to avoid typos
await Tyrads.instance.showOffers(route: TyradsDeepRoutes.OFFERS);

// Activated Campaigns Page
await Tyrads.instance.showOffers(route: "active-offers");
// or using TyradsDeepRoutes class like
await Tyrads.instance.showOffers(route: TyradsDeepRoutes.ACTIVE_OFFERS);

// Campaign Details Page (requires campaignID)
await Tyrads.instance.showOffers(route: "offer", campaignID: "your_campaign_id_here");
// or using TyradsDeepRoutes class like
await Tyrads.instance.showOffers(route: TyradsDeepRoutes.OFFER, campaignID: "your_campaign_id_here");

// Campaign Tickets Page (requires campaignID)
await Tyrads.instance.showOffers(route: "support", campaignID: "your_campaign_id_here");
// or using TyradsDeepRoutes class like
await Tyrads.instance.showOffers(route: TyradsDeepRoutes.SUPPORT, campaignID: "your_campaign_id_here");
```

***

### 4. Premium Offers Widget

The **PremiumOffersWidget** is a standalone UI element that displays a preview of top offers. It is highly flexible and can be embedded anywhere in your UI.

#### Integration

```dart
import 'package:tyrads_sdk/tyrads_sdk.dart';

class MyHomeView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const Text("Recommended for you:"),
        // Standalone widget — works without context parameters
        const PremiumOffersWidget(
          widgetStyle: PremiumWidgetStyles.sliderCards,
        ),
      ],
    );
  }
}
```

#### Widget Styles

* **`PremiumWidgetStyles.list`**: A standard vertical list layout (Default).
* **`PremiumWidgetStyles.sliderCards`**: A horizontal, swipeable card carousel.

**Available Widget Style options**

<figure><img src="/files/pmkTkVXEfP8BjgHKJ7SK" alt=""><figcaption><p>Option 1</p></figcaption></figure>

<figure><img src="/files/zMADmZXKS3LZtzT4sJkN" alt=""><figcaption><p>Option 2 </p></figcaption></figure>

***

### 5. Localization

You can change the SDK language dynamically at runtime. This choice is persisted across app sessions.

```dart
// Supported codes: en, es, id, ja, ko, zh-Hans-CN
await Tyrads.instance.changeLanguage("es"); // Change to Spanish
```

#### Parameters:

* `languageCode` (String): A string representing the desired language code (e.g., "en" for English, "es" for Spanish, "fr" for French). This should be a valid ISO 639-1 language code.

#### Notes:

* This method persists the selected language in shared preferences so that it persists between app sessions.
* Make sure your application and the Tyrads SDK support the language code you are passing, otherwise english will be set.
* This method is asynchronous because it involves writing to shared preferences.
* Consider providing a language selection UI in your application that allows users to choose their preferred language if not Sdk itself provides user to select prefered language.

***

### 6. Callbacks

Register callbacks to monitor user actions within the SDK:

```dart
Tyrads.instance.setCallback(TyradsCallbackType.activated, (data) {
  print("User activated a campaign: $data");
});

Tyrads.instance.setCallback(TyradsCallbackType.campaignDetail, (data) {
  print("User viewed campaign details: $data");
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sdk-doc.tyrads.com/flutter/initialization.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
