> ## Documentation Index
> Fetch the complete documentation index at: https://docs.adrop.io/llms.txt
> Use this file to discover all available pages before exploring further.

# ターゲティング設定

> Flutter SDKでターゲティングを設定する方法をご案内します。

## 概要

ターゲティング設定により、特定のユーザーグループにカスタマイズされた広告を表示できます。Adrop SDKは**オーディエンスターゲティング**方式を提供しています。

* **オーディエンスターゲティング**: ユーザーのプロパティ(属性)に基づいて広告を表示します。

<Note>
  ターゲティングデータを収集するには、広告ロード前にプロパティを設定する必要があります。
</Note>

***

## UIDの設定（オプション）

ユーザー識別子(UID)を設定して、プラットフォーム間でターゲティングデータを共有できます。UIDはオプションであり、プロパティベースおよびイベントベースのターゲティングには必要ありません。

### 使い方

```dart theme={null}
import 'package:adrop_ads_flutter/adrop_ads_flutter.dart';

// ユーザーログイン後（オプション）
await Adrop.setUID('user_123');

// ユーザーログアウト時
await Adrop.setUID('');
```

### パラメータ

| パラメータ | タイプ      | 説明                      |
| ----- | -------- | ----------------------- |
| `uid` | `String` | ユーザー固有識別子 (例: サービス会員ID) |

<Warning>
  UIDはSHA-256でハッシュ化されて送信されます。個人情報(メール、電話番号など)を直接渡さないでください。
</Warning>

<Note>
  ログアウト時は空の文字列(`''`)を渡してUIDを初期化してください。
</Note>

***

## オーディエンスターゲティング

ユーザーの属性情報(プロパティ)を収集して、特定のユーザーグループに広告を表示します。

### プロパティの設定

`AdropMetrics.setProperty()`メソッドを使用してユーザーの属性情報を収集します。

```dart theme={null}
import 'package:adrop_ads_flutter/adrop_ads_flutter.dart';

// 文字列プロパティ
await AdropMetrics.setProperty('membership_level', 'premium');

// 数値プロパティ
await AdropMetrics.setProperty('booking_count', 15);

// ブール値プロパティ
await AdropMetrics.setProperty('is_subscriber', true);

// nullを渡す (プロパティの削除)
await AdropMetrics.setProperty('membership_level', null);
```

### パラメータ

| パラメータ   | タイプ       | 説明                                       |
| ------- | --------- | ---------------------------------------- |
| `key`   | `String`  | プロパティキー (最大64文字)                         |
| `value` | `dynamic` | プロパティ値 (String, int, double, bool, null) |

<Warning>
  * プロパティキーは最大64文字まで可能です。
  * 文字列値は最大256文字まで可能です。
  * 数値は最大9007199254740991まで可能です。
  * 最大256個のプロパティを設定できます。
</Warning>

### デフォルトプロパティ

Adrop SDKはターゲティング用のデフォルトプロパティを提供しています。

#### 年齢 (生年月日)

生年月日情報を渡すと、自動的に年齢が計算されます。

```dart theme={null}
import 'package:adrop_ads_flutter/adrop_ads_flutter.dart';

// 年のみ (yyyy)
await AdropMetrics.setProperty('BIRTH', '1990');

// 年月 (yyyyMM)
await AdropMetrics.setProperty('BIRTH', '199003');

// 年月日 (yyyyMMdd)
await AdropMetrics.setProperty('BIRTH', '19900315');
```

**日付フォーマット**

| フォーマット     | 例          | 説明  |
| ---------- | ---------- | --- |
| `yyyy`     | "1990"     | 年のみ |
| `yyyyMM`   | "199003"   | 年月  |
| `yyyyMMdd` | "19900315" | 年月日 |

#### 性別

```dart theme={null}
import 'package:adrop_ads_flutter/adrop_ads_flutter.dart';

// 男性
await AdropMetrics.setProperty('GDR', 'M');

// 女性
await AdropMetrics.setProperty('GDR', 'F');

// その他
await AdropMetrics.setProperty('GDR', 'O');

// 未確認
await AdropMetrics.setProperty('GDR', 'U');
```

**性別の値**

| 値   | 説明  |
| --- | --- |
| `M` | 男性  |
| `F` | 女性  |
| `O` | その他 |
| `U` | 未確認 |

<Tip>
  SDKが提供する`AdropProperties`と`AdropGender`列挙型も使用できます：

  ```dart theme={null}
  import 'package:adrop_ads_flutter/adrop_ads_flutter.dart';

  await AdropMetrics.setProperty(AdropProperties.birth.code, '19900315');
  await AdropMetrics.setProperty(AdropProperties.gender.code, AdropGender.male.code);
  await AdropMetrics.setProperty(AdropProperties.age.code, 35);
  ```
</Tip>

#### 年齢を直接設定

生年月日の代わりに年齢を直接設定することもできます。

```dart theme={null}
await AdropMetrics.setProperty('AGE', 30);
```

<Note>
  `BIRTH`と`AGE`のいずれか一方のみ設定すればよいです。両方設定された場合、`BIRTH`が優先されます。
</Note>

### カスタムプロパティ

サービスに合ったカスタムプロパティを設定できます。カスタムプロパティは[Ad Controlコンソール](https://console.adrop.io)の**ターゲティング**メニューで最初に定義する必要があります。

```dart theme={null}
import 'package:adrop_ads_flutter/adrop_ads_flutter.dart';

// ローカルアクティビティアプリの例
await AdropMetrics.setProperty('region', 'Seoul');
await AdropMetrics.setProperty('booking_count', 5);

// ショッピングモールアプリの例
await AdropMetrics.setProperty('membership_tier', 'gold');
await AdropMetrics.setProperty('total_purchase_amount', 1500000);

// メディアアプリの例
await AdropMetrics.setProperty('favorite_genre', 'drama');
await AdropMetrics.setProperty('is_premium_subscriber', true);
```

<Warning>
  カスタムプロパティ名はコンソールで定義した名前と正確に一致する必要があります。大文字と小文字を区別します。
</Warning>

***

## イベント送信

ユーザー行動を追跡するためにイベントを送信できます。

### イベントを送信する

```dart theme={null}
import 'package:adrop_ads_flutter/adrop_ads_flutter.dart';

// イベント名のみ
await AdropMetrics.sendEvent('click');

// パラメータと共に
await AdropMetrics.sendEvent('purchase', {
  'item_id': 'SKU_001',
  'price': 29900,
  'currency': 'KRW',
});
```

### パラメータ

| パラメータ    | タイプ                     | 説明                                                |
| -------- | ----------------------- | ------------------------------------------------- |
| `name`   | `String`                | イベント名                                             |
| `params` | `Map<String, dynamic>?` | イベントパラメータ（オプション）。String、int、double、bool値をサポートします。 |

<Note>
  1つのイベントに最大20個のパラメータを設定できます。
</Note>

<Warning>
  `logEvent()`はバージョン1.8.0からdeprecatedされました。`sendEvent()`を使用してください。
</Warning>

***

## プロパティの照会

保存されたすべてのプロパティを照会できます。

```dart theme={null}
import 'package:adrop_ads_flutter/adrop_ads_flutter.dart';

final properties = await AdropMetrics.properties();
debugPrint('保存されたプロパティ: $properties');
```

***

## 使用例

### ログイン時にプロパティを設定

```dart theme={null}
import 'package:flutter/material.dart';
import 'package:adrop_ads_flutter/adrop_ads_flutter.dart';

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

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  Future<void> _onLoginSuccess(User user) async {
    // デフォルトプロパティを設定
    if (user.birthDate != null) {
      await AdropMetrics.setProperty('BIRTH', user.birthDate);
    }
    if (user.gender != null) {
      await AdropMetrics.setProperty('GDR', user.gender);
    }

    // カスタムプロパティを設定
    await AdropMetrics.setProperty('membership_level', user.membershipLevel);
    await AdropMetrics.setProperty('total_booking_count', user.bookingCount);

    // 会員登録イベントを送信
    await AdropMetrics.sendEvent('sign_up', {
      'method': 'email',
    });

    // メイン画面に移動
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(builder: (_) => const MainScreen()),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // ...
    );
  }
}
```

### ログアウト時に初期化

```dart theme={null}
Future<void> _onLogout() async {
  // 必要に応じてプロパティも初期化
  await AdropMetrics.setProperty('membership_level', null);
  await AdropMetrics.setProperty('total_booking_count', null);
}
```

### プロパティの更新

```dart theme={null}
class UserProfile extends StatelessWidget {
  void _onPurchaseComplete(int purchaseAmount) async {
    // 購入完了時にプロパティを更新
    final currentTotal = await _getCurrentTotalPurchase();
    await AdropMetrics.setProperty(
      'total_purchase_amount',
      currentTotal + purchaseAmount,
    );

    // 購入イベントを送信
    await AdropMetrics.sendEvent('purchase', {
      'amount': purchaseAmount,
      'currency': 'KRW',
    });
  }

  void _onMembershipUpgrade(String newTier) async {
    // メンバーシップアップグレード時にプロパティを更新
    await AdropMetrics.setProperty('membership_tier', newTier);

    // アップグレードイベントを送信
    await AdropMetrics.sendEvent('membership_upgrade', {
      'new_tier': newTier,
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
```

***

## ベストプラクティス

### 1. 広告ロード前にプロパティを設定

```dart theme={null}
// ✅ 正しい例
await AdropMetrics.setProperty('membership_level', 'premium');
// 広告をロード...
bannerView.load();

// ❌ 間違った例
bannerView.load();
await AdropMetrics.setProperty('membership_level', 'premium'); // 広告ロード後に設定するとターゲティングが適用されません
```

### 2. 変更されるたびにプロパティを更新

```dart theme={null}
class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    // アプリ起動時に初期プロパティを設定
    _updateUserProperties();
  }

  Future<void> _updateUserProperties() async {
    final user = await getUserInfo();
    await AdropMetrics.setProperty('membership_level', user.membershipLevel);
  }
}
```

### 3. ログアウト時にプロパティを初期化

```dart theme={null}
Future<void> onUserLogout() async {
  // 必要に応じてプロパティも初期化
  await AdropMetrics.setProperty('membership_level', null);
  await AdropMetrics.setProperty('total_booking_count', null);
}
```

***

## 関連ドキュメント

<CardGroup cols={2}>
  <Card title="オーディエンスターゲティングの作成" icon="users" href="/ja/targeting/audience">
    コンソールでオーディエンスターゲティングを作成する
  </Card>

  <Card title="ターゲティング販売" icon="won-sign" href="/ja/targeting/sell">
    ターゲティングカテゴリーの販売設定
  </Card>

  <Card title="バナー広告" icon="rectangle-ad" href="/ja/sdk/flutter/banner">
    バナー広告を実装する
  </Card>

  <Card title="ネイティブ広告" icon="mobile" href="/ja/sdk/flutter/native">
    ネイティブ広告を実装する
  </Card>
</CardGroup>

***

## FAQ

<AccordionGroup>
  <Accordion title="UIDを設定しないとターゲティング広告が表示されませんか?">
    UIDはオプションです。UIDを設定しなくても、プロパティベースおよびイベントベースのターゲティングは正常に動作します。UIDは複数のプラットフォーム間でターゲティングデータを共有する場合にのみ必要です。
  </Accordion>

  <Accordion title="プロパティを設定したのにコンソールにデータが表示されません。">
    プロパティデータは収集後、最大24時間以内にコンソールに反映されます。データが表示されない場合:

    1. コンソールでプロパティが正しく定義されているか確認してください。
    2. SDKから渡すプロパティキーがコンソールと正確に一致しているか確認してください(大文字小文字を区別)。
    3. `AdropMetrics.setProperty()`が広告ロード前に呼び出されているか確認してください。
  </Accordion>

  <Accordion title="プロパティ値を削除するにはどうすればよいですか?">
    プロパティ値に`null`を渡すと、そのプロパティが削除されます:

    ```dart theme={null}
    await AdropMetrics.setProperty('membership_level', null);
    ```
  </Accordion>

  <Accordion title="プロパティ値のタイプ制限はありますか?">
    サポートされているタイプは`String`、`int`、`double`、`bool`です。配列や複雑なオブジェクトはサポートされていません。必要な場合は文字列に変換して渡してください。
  </Accordion>
</AccordionGroup>
