Flutter腾讯云聊天投票功能插件tencent_cloud_chat_vote_plugin的使用

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

Flutter腾讯云聊天投票功能插件tencent_cloud_chat_vote_plugin的使用

插件内容

tencent_cloud_chat_sdk 5.1.5版本之后,您可以集成腾讯云即时通信官方提供的投票插件tencent_cloud_chat_vote_plugin。此插件为闭源插件,集成后,您可以在群里(Community和AVChatRoom除外)集成投票功能。投票功能包括发起(单选、多选)投票、查看投票结果,参与投票等。Flutter端与Native、Web端的投票能力互通。

注意: 投票是增值付费功能,当前处于内测阶段,请联系腾讯云商务为您开通后体验完整功能。

环境与版本

本插件依赖插件以及环境

插件引入

通过pub可将投票插件引入到项目中,插件地址:tencent_cloud_chat_vote_plugin

// 集成最新版本
pub add tencent_cloud_chat_vote_plugin

// 集成指定版本,在项目pubspec.yaml中dependencies字段加入
tencent_cloud_chat_vote_plugin: "version" 

核心组件

  • TencentCloudChatVoteCreate:创建投票
  • TencentCloudChatVoteMessage:投票消息解析
  • TencentCloudChatVoteDetail:投票详情展示

插件集成

创建投票

用户点击投票按钮,可创建投票

import 'package:example/config.dart';
import 'package:flutter/material.dart';
import 'package:tencent_cloud_chat_vote_plugin/components/vote_create/vote_create.dart';

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

  [@override](/user/override)
  State<StatefulWidget> createState() => VoteCreateExampleState();
}

class VoteCreateExampleState extends State {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("创建投票"),
      ),
      body: Container(
        padding: const EdgeInsets.all(16),
        child: TencentCloudChatVoteCreate(
          groupID: ExampleConfig.testGruopID,
          onCreateVoteSuccess: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}

TencentCloudChatVoteCreate参数说明

  • groupID:需要创建投票的群ID,同IM群ID,Community和AVChatRoom除外。
  • onCreateVoteSuccess:创建投票成功回调。

投票消息解析

import 'package:example/config.dart';
import 'package:example/vote_detail_example.dart';
import 'package:flutter/material.dart';
import 'package:tencent_cloud_chat_sdk/enum/history_msg_get_type_enum.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_value_callback.dart';
import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.dart';
import 'package:tencent_cloud_chat_vote_plugin/tencent_cloud_chat_vote_plugin.dart';

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

  [@override](/user/override)
  State<StatefulWidget> createState() => VoteMessageExampleState();
}

class VoteMessageExampleState extends State {
  V2TimMessage? message;
  getTestV2TimMessage() async {
    V2TimValueCallback<List<V2TimMessage>> messageListRes =
        await TencentImSDKPlugin.v2TIMManager
            .getMessageManager()
            .getHistoryMessageList(
              count: 1,
              groupID: ExampleConfig.testGruopID,
              getType: HistoryMsgGetTypeEnum.V2TIM_GET_CLOUD_OLDER_MSG,
            );
    if (messageListRes.code == 0) {
      if (messageListRes.data != null) {
        if (messageListRes.data!.isNotEmpty) {
          setState(() {
            message = messageListRes.data!.first;
          });
        }
      }
    }
  }

  bool isEnd = false;
  [@override](/user/override)
  void initState() {
    super.initState();
    Future.delayed(
        const Duration(
          milliseconds: 300,
        ), () {
      setState(() {
        isEnd = true;
      });
    });
    // 页面运动结束再显示组件
    getTestV2TimMessage();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("投票消息体"),
      ),
      body: !isEnd
          ? Container()
          : message != null
              ? TencentCloudChatVoteMessage(
                  message: message!,
                  onTap: (
                    TencentCloudChatVoteDataOptoin option,
                    TencentCloudChatVoteLogic data,
                  ) {
                    print(data.voteData.toJson());
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => VoteDetailExample(
                          option: option,
                          data: data,
                        ),
                      ),
                    );
                  },
                )
              : const Center(
                  child: Text("未获取到正确的Message实例"),
                ),
    );
  }
}

TencentCloudChatVoteMessage参数说明

  • message:投票消息,V2TimMessage类型。
  • onTap:点击投票回调,当投票为公开且实名时,可以打开群投票详情。

投票详情查看

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

class VoteDetailExample extends StatelessWidget {
  final TencentCloudChatVoteDataOptoin option;
  final TencentCloudChatVoteLogic data;
  const VoteDetailExample({
    super.key,
    required this.option,
    required this.data,
  });

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(option.option),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: TencentCloudChatVoteDetail(
          option: option,
          data: data,
        ),
      ),
    );
  }
}

TencentCloudChatVoteDetail参数说明

  • option:TencentCloudChatVoteDataOptoin类型,投票详情数据,由TencentCloudChatVoteMessage点击时获取。
  • data:TencentCloudChatVoteLogic类型由TencentCloudChatVoteMessage点击时获取。

完整示例Demo

import 'package:example/config.dart';
import 'package:example/vote_create_example.dart';
import 'package:example/vote_message_example.dart';
import 'package:flutter/material.dart';
import 'package:tencent_cloud_chat_sdk/enum/V2TimSDKListener.dart';
import 'package:tencent_cloud_chat_sdk/enum/log_level_enum.dart';
import 'package:tencent_cloud_chat_sdk/enum/v2_tim_plugins.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_callback.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_value_callback.dart';
import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.dart';
import 'package:tencent_cloud_chat_vote_plugin/tencent_cloud_chat_vote_plugin.dart';

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

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

  // This widget is the root of your application.
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  void initState() {
    super.initState();
    initIMSDK();
  }

  bool isLogined = false;
  final int sdkAppID = ExampleConfig.sdkAppID;
  final LogLevelEnum loglevel = ExampleConfig.loglevel;
  final V2TimSDKListener listener = V2TimSDKListener(
    onConnectFailed: (code, error) {},
    onConnectSuccess: () {
      print("connect to tencent cloud chat server successed");
    },
    onConnecting: () {
      print("connect to tencent cloud chat server...");
    },
    onKickedOffline: () {
      print("you are kicked");
    },
    onUserSigExpired: () {
      print("your usersig was expored");
    },
  );
  final String userID = ExampleConfig.userID;
  final String userSig = ExampleConfig.userSig;

  // 无UISDK 初始化登录imSDK
  initIMSDK() async {
    V2TimValueCallback<bool> initres = await TencentImSDKPlugin.v2TIMManager.initSDK(
      sdkAppID: sdkAppID,
      loglevel: loglevel,
      listener: listener,
      plugins: List.from([
        V2TimPlugins.Vote,
      ]),
    );
    if (initres.code == 0 && initres.data!) {
      V2TimCallback loginRes = await TencentImSDKPlugin.v2TIMManager.login(
        userID: userID,
        userSig: userSig,
      );
      if (loginRes.code == 0) {
        // 初始化投票插件
        await TencentCloudChatVotePlugin.initPlugin();
        setState(() {
          isLogined = true;
        });
      }
    }
  }

  openVoteTestPage(String pageName) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => pageName == "create"
            ? const VoteCreateExample()
            : pageName == "mesasge"
                ? const VoteMessageExample()
                : Container(),
      ),
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: isLogined
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Row(
                    children: [
                      Expanded(
                        child: ElevatedButton(
                          onPressed: () {
                            openVoteTestPage("create");
                          },
                          child: const Text("创建投票"),
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: ElevatedButton(
                          onPressed: () {
                            openVoteTestPage("mesasge");
                          },
                          child: const Text("投票消息体"),
                        ),
                      )
                    ],
                  ),
                ],
              ),
            )
          : const Center(
              child: Text("正在登录腾讯云即时通信,请稍候"),
            ),
    );
  }
}

更多关于Flutter腾讯云聊天投票功能插件tencent_cloud_chat_vote_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter腾讯云聊天投票功能插件tencent_cloud_chat_vote_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用tencent_cloud_chat_vote_plugin插件来实现聊天和投票功能的示例代码。请注意,这只是一个示例,具体实现可能会根据插件的实际API和腾讯云的具体服务有所调整。假设tencent_cloud_chat_vote_plugin插件已经正确安装并配置在你的Flutter项目中。

1. 插件安装与配置

首先,确保你已经在pubspec.yaml文件中添加了tencent_cloud_chat_vote_plugin依赖,并运行flutter pub get来安装它。

dependencies:
  flutter:
    sdk: flutter
  tencent_cloud_chat_vote_plugin: ^x.y.z  # 替换为实际版本号

2. 初始化插件

在你的应用启动时(例如在main.dart中),初始化腾讯云聊天和投票插件。

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化插件
  TencentCloudChatVotePlugin.initialize(
    apiKey: 'YOUR_API_KEY',  // 替换为你的腾讯云API Key
    secretKey: 'YOUR_SECRET_KEY',  // 替换为你的腾讯云Secret Key
    region: 'YOUR_REGION',  // 替换为你的腾讯云服务区域
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChatVoteScreen(),
    );
  }
}

3. 实现聊天功能

ChatVoteScreen中,实现基本的聊天功能。

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

class ChatVoteScreen extends StatefulWidget {
  @override
  _ChatVoteScreenState createState() => _ChatVoteScreenState();
}

class _ChatVoteScreenState extends State<ChatVoteScreen> {
  final TextEditingController _messageController = TextEditingController();
  List<ChatMessage> _messages = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Chat and Vote'),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(_messages[index].content),
                  subtitle: Text(_messages[index].sender),
                );
              },
            ),
          ),
          TextField(
            controller: _messageController,
            decoration: InputDecoration(
              labelText: 'Enter message',
            ),
          ),
          ElevatedButton(
            onPressed: () async {
              String message = _messageController.text;
              if (message.isNotEmpty) {
                // 发送消息
                await TencentCloudChatVotePlugin.sendMessage(
                  roomId: 'ROOM_ID',  // 替换为你的聊天室ID
                  content: message,
                );
                // 更新本地消息列表(假设插件没有提供实时消息监听)
                setState(() {
                  _messages.add(ChatMessage(
                    content: message,
                    sender: 'Me',  // 这里简单处理为“Me”,实际中可能需要从用户信息中获取
                  ));
                  _messageController.clear();
                });
              }
            },
            child: Text('Send'),
          ),
        ],
      ),
    );
  }
}

class ChatMessage {
  String content;
  String sender;

  ChatMessage({required this.content, required this.sender});
}

4. 实现投票功能

ChatVoteScreen中,添加投票功能的按钮和逻辑。

// 在_ChatVoteScreenState类的build方法中添加投票按钮和逻辑

// ... 其他代码 ...

ElevatedButton(
  onPressed: () async {
    // 显示投票选项(这里简单处理为固定选项,实际中可能需要从服务器获取)
    List<String> options = ['Option 1', 'Option 2', 'Option 3'];
    String selectedOption = await showDialog<String>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Vote'),
          content: SingleChildScrollView(
            child: ListBody(
              children: List.generate(options.length, (index) {
                return GestureDetector(
                  onTap: () {
                    Navigator.of(context).pop(options[index]);
                  },
                  child: Text(options[index]),
                );
              }),
            ),
          ),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('Cancel'),
            ),
          ],
        );
      },
    );

    if (selectedOption != null) {
      // 发送投票结果
      await TencentCloudChatVotePlugin.sendVote(
        roomId: 'ROOM_ID',  // 替换为你的聊天室ID
        option: selectedOption,
      );
      // 更新UI或处理投票结果(这里简单处理为打印输出)
      print('Vote cast for: $selectedOption');
    }
  },
  child: Text('Vote'),
),

// ... 其他代码 ...

注意事项

  1. API Key和Secret Key:确保不要将API Key和Secret Key硬编码在客户端代码中,考虑使用更安全的方法,如环境变量或后端服务。
  2. 错误处理:示例代码中没有包含错误处理逻辑,实际开发中应添加适当的错误处理。
  3. 实时性:示例代码中假设插件不提供实时消息监听,如果插件支持,应使用实时监听来更新消息列表。
  4. UI设计:示例代码中的UI设计非常基础,实际开发中应根据产品需求进行更详细的设计。

希望这个示例能帮助你在Flutter项目中集成tencent_cloud_chat_vote_plugin插件并实现聊天和投票功能。

回到顶部