Flutter对话流管理插件dialogflow_flutter_plus的使用

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

Flutter对话流管理插件dialogflow_flutter_plus的使用

dialogflow_flutter_plus 是一个帮助用户在他们的应用中使用 Dialogflow 聊天机器人的 Flutter 插件。

支持项目

欢迎提供建议和 Pull Requests!

安装

  1. 在你的 pubspec.yaml 文件中添加以下依赖:
dependencies:
  dialogflow_flutter_plus: ^0.0.1
  1. 使用命令行安装包:
$ flutter packages get

平台支持

Android iOS MacOS Web Linux Windows
✔️ ✔️ ✔️ ✔️ ✔️

示例代码

以下是完整的示例代码,展示如何使用 dialogflow_flutter_plus 插件来创建一个聊天机器人界面。

import 'package:bubble/bubble.dart';
import 'package:dialogflow_flutter_plus/googleAuth.dart';
import 'package:flutter/material.dart';
import 'package:dialogflow_flutter_plus/dialogflowFlutter.dart';

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: Colors.blue,
        primarySwatch: Colors.blue,
      ),
      home: ChatBotScreen(),
    );
  }
}

class ChatBotScreen extends StatefulWidget {
  [@override](/user/override)
  ChatBotScreenState createState() => ChatBotScreenState();
}

class ChatBotScreenState extends State<ChatBotScreen> {
  final messageInsert = TextEditingController();
  List<Map> messages = [];

  // 响应用户的查询
  void response(String query) async {
    AuthGoogle authGoogle = await AuthGoogle(fileJson: "assets/farmtech-fh9j-3db6e0409c71.json").build();
    DialogFlow dialogflow = DialogFlow(authGoogle: authGoogle, language: "en");
    AIResponse aiResponse = await dialogflow.detectIntent(query);
    setState(() {
      messages.insert(0, {
        "data": 0,
        "message": aiResponse.getListMessage()?.first["text"]["text"].first.toString()
      });
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        toolbarHeight: 70,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            bottomLeft: Radius.circular(30),
            bottomRight: Radius.circular(30),
          ),
        ),
        elevation: 10,
        title: Text("Dailog Flow Chatbot"),
      ),
      body: Container(
        child: Column(
          children: [
            Flexible(
              child: ListView.builder(
                reverse: true,
                itemCount: messages.length,
                itemBuilder: (context, index) => chat(messages[index]["message"].toString(), messages[index]["data"]),
              ),
            ),
            Divider(height: 6.0),
            Container(
              padding: EdgeInsets.only(left: 15.0, right: 15.0, bottom: 20),
              margin: const EdgeInsets.symmetric(horizontal: 8.0),
              child: Row(
                children: [
                  Flexible(
                    child: TextField(
                      controller: messageInsert,
                      decoration: InputDecoration.collapsed(
                        hintText: "Send your message",
                        hintStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0),
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.symmetric(horizontal: 4.0),
                    child: IconButton(
                      icon: Icon(Icons.send, size: 30.0),
                      onPressed: () {
                        if (messageInsert.text.isEmpty) {
                          print("empty message");
                        } else {
                          setState(() {
                            messages.insert(0, {"data": 1, "message": messageInsert.text});
                          });
                          response(messageInsert.text);
                          messageInsert.clear();
                        }
                      },
                    ),
                  )
                ],
              ),
            ),
            SizedBox(height: 15.0)
          ],
        ),
      ),
    );
  }

  // 构建聊天消息
  Widget chat(String message, int data) {
    return Padding(
      padding: EdgeInsets.all(10.0),
      child: Bubble(
        radius: Radius.circular(15.0),
        color: data == 0 ? Colors.blue : Colors.orangeAccent,
        elevation: 0.0,
        alignment: data == 0 ? Alignment.topLeft : Alignment.topRight,
        nip: data == 0 ? BubbleNip.leftBottom : BubbleNip.rightTop,
        child: Padding(
          padding: EdgeInsets.all(2.0),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircleAvatar(
                backgroundImage: AssetImage(data == 0 ? "assets/bot.png" : "assets/user.png"),
              ),
              SizedBox(width: 10.0),
              Flexible(
                child: Text(
                  message,
                  style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter对话流管理插件dialogflow_flutter_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter对话流管理插件dialogflow_flutter_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


dialogflow_flutter_plus 是一个用于在 Flutter 应用中集成 Dialogflow(现为 Google Cloud 的 Dialogflow)对话流管理的插件。它允许你轻松地与 Dialogflow 代理进行交互,发送用户输入并接收来自 Dialogflow 的响应。

以下是使用 dialogflow_flutter_plus 插件的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 dialogflow_flutter_plus 依赖:

dependencies:
  flutter:
    sdk: flutter
  dialogflow_flutter_plus: ^1.0.0

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

2. 获取 Dialogflow 凭据

要使用 Dialogflow,你需要从 Google Cloud 控制台获取服务账户的 JSON 凭据文件。

  1. 打开 Google Cloud Console
  2. 创建一个项目(如果还没有)。
  3. 在项目中启用 Dialogflow API。
  4. 创建一个服务账户,并为其分配 Dialogflow API 的访问权限。
  5. 下载服务账户的 JSON 凭据文件。

3. 初始化 Dialogflow

在你的 Flutter 代码中,初始化 Dialogflow 对象。你需要提供从 Google Cloud 控制台下载的 JSON 凭据文件。

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

class ChatScreen extends StatefulWidget {
  [@override](/user/override)
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final Dialogflow _dialogflow = Dialogflow(
    serviceAccountCredentials:
        'YOUR_SERVICE_ACCOUNT_CREDENTIALS_JSON_CONTENT',
  );

  List<Map<String, String>> messages = [];

  void sendMessage(String message) async {
    setState(() {
      messages.add({"message": message, "isUser": "true"});
    });

    DetectIntentResponse response = await _dialogflow.detectIntent(
      queryInput: QueryInput(text: TextInput(text: message)),
    );

    setState(() {
      messages.add({"message": response.queryResult.fulfillmentText, "isUser": "false"});
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Chat with Dialogflow'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: messages.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(messages[index]["message"]!),
                  subtitle: Text(messages[index]["isUser"] == "true" ? "User" : "Bot"),
                );
              },
            ),
          ),
          TextField(
            onSubmitted: (value) {
              sendMessage(value);
            },
            decoration: InputDecoration(
              hintText: 'Type a message...',
            ),
          ),
        ],
      ),
    );
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!