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

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

dialogflow_flutter 是一个帮助用户在应用程序中使用Dialogflow聊天机器人的Flutter插件。

支持项目

⭐ 如果你想支持这个项目,请考虑给项目提供建议或提交拉取请求!

安装

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

平台支持

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

示例代码

下面是使用 dialogflow_flutter 插件创建聊天机器人的完整示例代码。

import 'package:bubble/bubble.dart';
import 'package:dialogflow_flutter/googleAuth.dart';
import 'package:flutter/material.dart';
import 'package:dialogflow_flutter/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 = List();

  // 响应用户输入并调用DialogFlow API获取回复
  void response(query) async {
    // 使用Google认证信息初始化DialogFlow对象
    AuthGoogle authGoogle = await AuthGoogle(fileJson: "assets/farmtech-fh9j-3db6e0409c71.json").build();
    DialogFlow dialogflow = DialogFlow(authGoogle: authGoogle, language: "en");

    // 调用detectIntent方法获取AI回复
    AIResponse aiResponse = await dialogflow.detectIntent(query);

    // 更新UI以显示AI回复
    setState(() {
      messages.insert(0, {
        "data": 0,
        "message": aiResponse.getListMessage()[0]["text"]["text"][0].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: "发送您的消息",
                        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("空消息");
                        } 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的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用dialogflow_flutter插件来管理对话流的示例代码。这个示例将展示如何初始化Dialogflow客户端、发送文本消息并处理响应。

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

dependencies:
  flutter:
    sdk: flutter
  dialogflow_flutter: ^0.x.x  # 请替换为最新版本号

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

接下来,创建一个Flutter项目,并在项目中使用以下代码:

1. 创建Dialogflow项目并获取凭证

在使用dialogflow_flutter之前,你需要在Dialogflow平台上创建一个项目,并生成一个服务账户凭证(通常是一个JSON文件)。确保你已经下载了这个凭证文件,并将其放置在Flutter项目的合适位置(例如assets/目录)。

2. 初始化Dialogflow客户端

在你的Flutter项目中,初始化Dialogflow客户端,并发送消息。下面是一个完整的示例代码:

import 'package:flutter/material.dart';
import 'package:dialogflow_flutter/dialogflow_flutter.dart';
import 'dart:convert';
import 'dart:io';

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

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

class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final TextEditingController _controller = TextEditingController();
  String _responseText = '';
  Dialogflow dialogflow;

  @override
  void initState() {
    super.initState();
    // 加载服务账户凭证
    rootBundle.loadString('assets/your-service-account-file.json').then((String contents) {
      final Map<String, dynamic> credentials = jsonDecode(contents);
      dialogflow = Dialogflow(
        credentials: credentials,
        projectId: 'your-project-id', // 替换为你的Dialogflow项目ID
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dialogflow Chat'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              _responseText,
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 20),
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Send a message',
              ),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: () async {
                if (_controller.text.isNotEmpty) {
                  try {
                    AIResponse response = await dialogflow.detectIntent(
                      text: _controller.text,
                      languageCode: 'en-US',
                    );
                    setState(() {
                      _responseText += 'Bot: ${response.queryResult.fulfillmentText}\n';
                    });
                  } catch (e) {
                    setState(() {
                      _responseText += 'Error: $e\n';
                    });
                  }
                  _controller.clear();
                }
              },
              child: Text('Send'),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

注意事项

  1. 凭证文件:确保将你的服务账户凭证文件(JSON格式)放在assets/目录下,并在pubspec.yaml中声明它:

    flutter:
      assets:
        - assets/your-service-account-file.json
    
  2. 错误处理:在实际应用中,你可能需要更详细的错误处理逻辑。

  3. 安全性:不要将敏感信息硬编码在代码中,特别是服务账户凭证。考虑使用环境变量或安全的存储机制。

这个示例展示了如何在Flutter应用中使用dialogflow_flutter插件来与Dialogflow进行交互。你可以根据实际需求进一步扩展和优化这个示例。

回到顶部