---
title: "在 Flutter SDK 中检查订阅状态"
description: "了解如何在 Flutter 应用中使用 Adapty 检查订阅状态。"
---

要决定用户是否可以访问付费内容或查看付费墙，您需要检查其用户画像中的[访问等级](access-level)。

本文介绍如何访问用户画像状态，以决定向用户展示什么内容——是显示付费墙还是授予付费功能访问权限。

## 获取订阅状态 \{#get-subscription-status\}

当您决定是否向用户显示付费墙或付费内容时，需要检查其用户画像中的[访问等级](access-level)。您有两种选择：

- 如果需要立即获取最新用户画像数据（例如应用启动时）或希望强制更新，请调用 `getProfile`。
- 设置**自动用户画像更新**，以保留一份本地副本，该副本会在订阅状态发生变化时自动刷新。

### 获取用户画像 \{#get-profile\}

获取订阅状态最简单的方法是使用 `getProfile` 方法访问用户画像：

```dart showLineNumbers
try {
  final profile = await Adapty().getProfile();
  // check the access
} on AdaptyError catch (adaptyError) {
  // handle the error
} catch (e) {
}
```

### 监听订阅更新 \{#listen-to-subscription-updates\}

要在应用中自动接收用户画像更新：

1. 使用 `Adapty().didUpdateProfileStream.listen()` 监听用户画像变更——每当用户的订阅状态发生变化时，Adapty 会自动调用此方法。
2. 在此方法被调用时保存更新后的用户画像数据，这样无需额外发起网络请求，即可在应用各处直接使用。
```dart
class SubscriptionManager {
  AdaptyProfile? _currentProfile;
  
  SubscriptionManager() {
    // Listen for profile updates
    Adapty().didUpdateProfileStream.listen((profile) {
      _currentProfile = profile;
      // Update UI, unlock content, etc.
    });
  }
  
  // Use stored profile instead of calling getProfile()
  bool hasAccess() {
    return _currentProfile?.accessLevels['premium']?.isActive ?? false;
  }
}
```

:::note
Adapty 会在应用启动时自动调用用户画像更新流监听器，即使设备处于离线状态，也能提供已缓存的订阅数据。
:::
## 将用户画像与付费墙逻辑关联 \{#connect-profile-with-paywall-logic\}

当你需要立即决定是否显示付费墙或授予付费功能访问权限时，可以直接检查用户的用户画像。这种方式适用于应用启动、进入高级功能区域或展示特定内容之前等场景。
```dart
Future<bool> _checkAccessLevel() async {
  try {
    final profile = await Adapty().getProfile();
    return profile.accessLevels['YOUR_ACCESS_LEVEL']?.isActive ?? false;
  } catch (e) {
    print('Error checking access level: $e');
    return false; // Show paywall if access check fails
  }
}

Future<void> _initializePaywall() async {
  await _loadPaywall();
  
  final hasAccess = await _checkAccessLevel();
  if (!hasAccess) {
    // Show paywall if no access
  }
}
``` 

## 后续步骤 \{#next-steps\}

现在您已了解如何追踪订阅状态，接下来请学习如何[管理用户画像](flutter-quickstart-identify)，以确保用户能够访问其已付费的内容。