Flutter Twitch客户端插件twitch_client的使用

发布于 1周前 作者 nodeper 来自 Flutter

Flutter Twitch 客户端插件 twitch_client 的使用

🚧 工作进行中 🚧

📝 注意:事件订阅仍在进行中,但自 Beta 版发布以来,您可以使用 0.0.8 版本开始尝试。

Twitch 客户端 🎮🎙

Twitch 客户端是一个包,它允许您连接到 Twitch API 并与数据交互,如 Bits、频道、聊天、游戏和管理。您可以在此处找到 Twitch API 文档。

功能

开始使用

此处 注册一个应用。 重定向 URL 和客户端 ID 是连接到 API 所必需的。

使用方法

创建一个 TwitchInterface 对象。

var twitchInterface = TwitchInterface(
    redirectionURL: 'url',
    clientid: 'clientID');

获取您将在 Web 视图中使用的 URL,以便让用户通过其帐户连接。 getConnectionUrl 方法需要一个作用域列表,所有作用域都在库中可用。

final uri = twitchInterface.getConnectionUrl(
              scopes: TwitchApiScopes.allScopes);

一旦连接完成,重定向 URL 将包含用户的访问令牌。 类似这样的东西: 将登录后返回的 URL 提供给包,它会解析该 URL 以保留访问令牌并将其添加到 TwitchInterface 中,此信息不会跨会话保留,您需要自己实现此逻辑。

twitchInterface.init(url: 'url');

现在您应该已连接,以下是如何调用方法:

  final data = await twitchInterface.streamsRepository.getFollowedStreams(props: GetFollowedStreamsProps(userId: twitchInterface.userId));

要获取连接的用户 ID:

twitchInterface.userId

其他信息

验证令牌 ⚠️

根据 Twitch 文档,您应该每小时验证一次访问令牌,他们可以审核您的应用程序并在不执行此操作时要求您解决该问题。 更多信息请参阅 这里

请调用 validateToken() 来执行此请求。

目前可用的请求

  • 启动商业广告
  • 获取扩展分析
  • 获取游戏分析
  • 获取 Bits 排行榜
  • 获取加油声
  • 获取频道信息
  • 修改频道信息
  • 获取频道编辑者
  • 获取关注的频道
  • 获取频道关注者
  • 获取聊天者
  • 获取聊天设置
  • 更新聊天设置
  • 禁止用户
  • 解除禁止用户
  • 获取管理员
  • 添加频道管理员
  • 删除频道管理员
  • 获取 VIP
  • 添加频道 VIP
  • 删除频道 VIP
  • 获取投票
  • 创建投票
  • 结束投票
  • 获取预测
  • 创建预测
  • 结束预测
  • 获取用户
  • 更新用户
  • 获取用户关注
  • 获取用户屏蔽列表
  • 屏蔽用户
  • 取消屏蔽用户
  • 获取视频
  • 删除视频
  • 创建自定义奖励
  • 删除自定义奖励
  • 获取自定义奖励
  • 获取自定义奖励兑换
  • 更新自定义奖励
  • 更新自定义奖励兑换
  • 获取直播
  • 获取关注的直播
  • 获取直播密钥
  • 发送聊天公告
  • 添加屏蔽词
  • 获取屏蔽词
  • 删除屏蔽词
  • 创建剪辑
  • 获取剪辑
  • 获取自动模式设置
  • 更新自动模式设置
  • 获取主播订阅
  • 开始突袭
  • 取消突袭
  • 获取热门游戏
  • 获取游戏

完整示例

以下是完整的示例代码:

import 'package:flutter/material.dart';
import 'package:twitch_client/twitch_client.dart';
import 'package:url_launcher/url_launcher.dart';

/// 添加您的重定向 URL 和 ClientId
/// 这里我使用 --dart-define=REDIRECTION=<URL> 作为运行参数
final twitchInterface = TwitchInterface(
    redirectionURL: const String.fromEnvironment('REDIRECTION'),
    clientId: const String.fromEnvironment('ID'));

void main() {
  runApp(const ExampleApp());
}

class ExampleApp extends StatelessWidget {
  const ExampleApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  const Home({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          TextButton(
              onPressed: () async {
                final uri = twitchInterface.getConnectionUrl(
                    scopes: TwitchApiScopes.allScopes);
                // 启动 Web 视图并检索重定向 URL(使用您喜欢的方式)
                await launchUrl(uri);
              },
              child: const Text('启动授权 URL')),
          TextButton(
              onPressed: () async {
                // 调用 init 方法并传入重定向后的 URL
                await twitchInterface.init(
                    url: const String.fromEnvironment('URL'));
              },
              child: const Text('解析 URL 并初始化库')),
          TextButton(
              onPressed: () async {
                // 调用 startRaid 方法
                final response = await twitchInterface.raid.startRaid(
                    props: RaidProps(
                        fromBroadcasterId: twitchInterface.userId,
                        toBroadcasterId: '123'));
              },
              child: const Text('突袭一个频道')),
          TextButton(
              onPressed: () async {
                final stream = await twitchInterface.event.subscribeTo(
                    type: TwitchSubscriptionType.channelUpdate,
                    userId: twitchInterface.userId);
                stream.listen((event) {
                  print(event.runtimeType);
                  if (event.runtimeType == WSEventResponse) {
                    /// 通常是一个连接状态
                  } else if (event.runtimeType == SubscriptionEvent) {
                    /// 您订阅的实际事件
                    final ev = event as SubscriptionEvent;
                    print('接收到事件 ${ev.subscriptionType}');
                    print('接收到事件 ${ev.event?.title}');
                  }
                });
              },
              child: const Text('WebSocket')),
          TextButton(
            child: const Text('获取关注的直播'),
            onPressed: () async {
              final data = await twitchInterface.streamsRepository
                  .getFollowedStreams(
                      props: GetFollowedStreamsProps(
                          userId: twitchInterface.userId));
              data.fold(
                  (l) => print(l.exception),
                  (r) => showDialog(
                      context: context,
                      builder: (context) {
                        return AlertDialog(
                            content: SizedBox(
                          height: MediaQuery.of(context).size.height / 2,
                          width: MediaQuery.of(context).size.width / 2,
                          child: ListView.builder(
                              shrinkWrap: true,
                              itemBuilder: (context, index) {
                                return Text(
                                    r.data?[index].toString() ?? '无名称');
                              },
                              itemCount: r.data?.length ?? 0),
                        ));
                      }));
            },
          ),
          TextButton(
            child: const Text('获取热门游戏'),
            onPressed: () async {
              final data = await twitchInterface.games
                  .getTopGames();
              data.fold(
                      (l) => print(l.exception),
                      (r) => showDialog(
                      context: context,
                      builder: (context) {
                        return AlertDialog(
                            content: SizedBox(
                              height: MediaQuery.of(context).size.height / 2,
                              width: MediaQuery.of(context).size.width / 2,
                              child: ListView.builder(
                                  shrinkWrap: true,
                                  itemBuilder: (context, index) {
                                    return Text(
                                        r.data?[index].toString() ?? '无名称');
                                  },
                                  itemCount: r.data?.length ?? 0),
                            ));
                      }));
            },
          ),
          TextButton(
            child: const Text('获取游戏'),
            onPressed: () async {
              final data = await twitchInterface.games
                  .getGames(props: GameProps(id: '33214'));
              data.fold(
                      (l) => print(l.exception),
                      (r) => showDialog(
                      context: context,
                      builder: (context) {
                        return AlertDialog(
                            content: SizedBox(
                              height: MediaQuery.of(context).size.height / 2,
                              width: MediaQuery.of(context).size.width / 2,
                              child: ListView.builder(
                                  shrinkWrap: true,
                                  itemBuilder: (context, index) {
                                    return Text(
                                        r.data?[index].toString() ?? '无名称');
                                  },
                                  itemCount: r.data?.length ?? 0),
                            ));
                      }));
            },
          )
        ],
      ),
    );
  }
}

更多关于Flutter Twitch客户端插件twitch_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Twitch客户端插件twitch_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用twitch_client插件的示例代码。这个插件允许你与Twitch API进行交互,从而获取流信息、用户信息等。请注意,实际使用时你需要替换成你自己的Twitch Client ID和Client Secret。

首先,确保你已经在pubspec.yaml文件中添加了twitch_client依赖:

dependencies:
  flutter:
    sdk: flutter
  twitch_client: ^最新版本号  # 替换为实际可用的最新版本号

然后运行flutter pub get来安装依赖。

接下来,你需要设置Twitch的Client ID和Client Secret。在实际应用中,这些敏感信息通常存储在环境变量或加密的配置文件中,但为了简化示例,这里直接在代码中硬编码(不推荐在生产环境中这样做)。

import 'package:flutter/material.dart';
import 'package:twitch_client/twitch_client.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  TwitchClient? _twitchClient;
  String? _userInfo;

  @override
  void initState() {
    super.initState();
    // 初始化TwitchClient,替换为你的Client ID和Client Secret
    final clientId = '你的Client ID';
    final clientSecret = '你的Client Secret';
    _twitchClient = TwitchClient(clientId: clientId, clientSecret: clientSecret);

    // 获取用户信息示例(这里使用了一个假用户ID,你需要替换为实际的用户ID)
    _getUserInfo('12345678'); // 替换为实际的用户ID
  }

  Future<void> _getUserInfo(String userId) async {
    try {
      final user = await _twitchClient!.getUsers(userIds: [userId]).first;
      setState(() {
        _userInfo = '用户名: ${user.displayName}, 登录名: ${user.login}';
      });
    } catch (e) {
      setState(() {
        _userInfo = '获取用户信息失败: ${e.message}';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Twitch Client Example'),
        ),
        body: Center(
          child: Text(_userInfo ?? '加载中...'),
        ),
      ),
    );
  }
}

在这个示例中,我们做了以下几件事:

  1. pubspec.yaml中添加了twitch_client依赖。
  2. MyApp组件的initState方法中初始化了TwitchClient实例。
  3. 使用_twitchClient实例调用getUsers方法来获取指定用户的信息。
  4. 将获取到的用户信息显示在页面上。

请注意,由于twitch_client插件的具体API可能会随着版本的更新而变化,因此请参考该插件的官方文档和源代码以获取最新的使用方法和API细节。

此外,由于Twitch API的使用可能涉及身份验证和授权,因此在实际应用中,你可能还需要处理OAuth2流程来获取用户的访问令牌,这里为了简化示例没有包含这部分内容。如果你需要实现完整的身份验证和授权流程,请参考Twitch API的官方文档。

回到顶部