flutter chatbot

Create chatbot apps in flutter is super easy, there is no complex configuration, this tutorial will learn how to create chatbot in flutter.

Introduction

What is Chatbot?

Chatbot is an artificial intelligent (AI) that can stimulate conversation (for instance text or voice conversation) with using a user natural language through message application, website, mobile apps and other platform. It can help many industry to grow up their business, with simplicity and fast response, chatbot can be reliable to provide information to users or customers. For example, chatbot can implement as customer service in our platform, it can handle basic information questions such as ask the office address, how to claim product, how to order product and many more.

Dialogflow

Dialogflow is a Google Service that runs on Google Cloud Platform, it’s a Google machine learning technologies based on user natural language conversation. Its give users new ways to interact with your product by building engaging voice and text-based conversationail interfaces, such as voice apps and chatbots, powered by AI. Connect with users on your website, mobile app, the Google Assistant, Amazon Alexa, Facebook Messenger, and other popular platforms and devices.

Currently, Dialogflow allowed us to get free access to create project, unfortunately, we just can create only 2 project for free.

Get started…!!!

Create a chatbot app with dialog box is quite easy, however in some cases its quite tricky to do that, so please follow carefully to get perfect result.

First, let’s just create agent in Dialogflow, login to Dialogflow using google account, follow this video to create chatbot conversation in detail.

Once you done follow video above, let’s create flutter project, add package flutter dialogflow version 2 in file pubspec.yaml

flutter_dialogflow_v2: ^0.3.1

Save that file and package will installed to your project.

Generate Authentication JSON

Now let’s download file JSON to get authentication to Dialogflow project:

  1. Go to Google Console
  2. Click here to see all list project
flutter chatbot dialogflow
  1. Find you dialogflow project you’ve created, usually when you create dialogflow, it will automatically create project in your console, so just find it in list.
    In case you are confuse about which project that you use, please notice your dialogflow project url, then you will see name of your project.
flutter chatbot dialogflow.
Dialogflow Project
google console project list all
Google Console Project List All
  1. Click project name in your google console, and go to Credentials, you will see numbers of service account exists. In order to choose correct account for credential dialogflow, just go back to Dialogflow project and take a look at Google Project section and look at in Service Account, that is account that we will work in google console project. Just remember that account
dialogflow google project
dialogflow google console service account
  1. After you find out correct account, then click it and you will bring to new window. Click ADD KEY and choose Create New Key
  1. Popup will coming, just choose key type JSON and click Create.
dialogflow google consol generate authentication key
  1. Wait until process done, one its done, you will get authentication file JSON for your project Dialogflow.
dialogflow google console generate authentication file json

Afterward, now let’s just go back to Flutter project, copy file json to your project assets, then create new file as chatbot.dart then put this code.

Chatbot.dart

import 'package:flutter_dialogflow_v2/flutter_dialogflow_v2.dart' as df;
import 'package:flutter/material.dart';

class ChatbotDialogflow extends StatefulWidget {
  ChatbotDialogflow({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _ChatbotDialogflowState createState() => new _ChatbotDialogflowState();
}

class _ChatbotDialogflowState extends State<ChatbotDialogflow> {
  final List<ChatMessage> _messages = <ChatMessage>[];
  final TextEditingController _textController = new TextEditingController();

  Widget _buildTextComposer() {
    return new IconTheme(
      data: new IconThemeData(color: Theme.of(context).accentColor),
      child: new Container(
        margin: const EdgeInsets.symmetric(horizontal: 8.0),
        child: new Row(
          children: <Widget>[
            new Flexible(
              child: new TextField(
                controller: _textController,
                onSubmitted: _handleSubmitted,
                decoration:
                    new InputDecoration.collapsed(hintText: 'Send a message'),
              ),
            ),
            new Container(
              margin: new EdgeInsets.symmetric(horizontal: 4.0),
              child: new IconButton(
                  icon: new Icon(Icons.send),
                  onPressed: () => _handleSubmitted(_textController.text)),
            ),
          ],
        ),
      ),
    );
  }

  void response(query) async {
    _textController.clear();
    df.AuthGoogle authGoogle =
        await df.AuthGoogle(fileJson: 'assets/credential-dialogflow.json').build();
    df.Dialogflow dialogflow =
        df.Dialogflow(authGoogle: authGoogle, sessionId: '123456');
    df.DetectIntentResponse response = await dialogflow.detectIntentFromText(query, "id");
    ChatMessage message = new ChatMessage(
      text: response.queryResult.fulfillmentText,
      name: 'Munaroh',
      type: false,
    );
    setState(() {
      _messages.insert(0, message);
    });
  }

  void _handleSubmitted(String text) {
    _textController.clear();
    ChatMessage message = new ChatMessage(
      text: text,
      name: 'Djanuar',
      type: true,
    );
    setState(() {
      _messages.insert(0, message);
    });
    response(text);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Chat Me'),
      ),
      body: new Column(children: <Widget>[
        new Flexible(
            child: new ListView.builder(
          padding: new EdgeInsets.all(8.0),
          reverse: true,
          itemBuilder: (_, int index) => _messages[index],
          itemCount: _messages.length,
        )),
        new Divider(height: 1.0),
        new Container(
          decoration: new BoxDecoration(color: Theme.of(context).cardColor),
          child: _buildTextComposer(),
        ),
      ]),
    );
  }
}

class ChatMessage extends StatelessWidget {
  ChatMessage({this.text, this.name, this.type});

  final String text;
  final String name;
  final bool type;

  List<Widget> otherMessage(context) {
    return <Widget>[
      new Container(
        margin: const EdgeInsets.only(right: 16.0),
        child: new CircleAvatar(backgroundImage: AssetImage("assets/girls.jpg"),),
      ),
      new Expanded(
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            new Text(this.name,
                style: new TextStyle(fontWeight: FontWeight.bold)),
            new Container(
              margin: const EdgeInsets.only(top: 5.0),
              child: new Text(text),
            ),
          ],
        ),
      ),
    ];
  }

  List<Widget> myMessage(context) {
    return <Widget>[
      new Expanded(
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            new Text(this.name, style: Theme.of(context).textTheme.subhead),
            new Container(
              margin: const EdgeInsets.only(top: 5.0),
              child: new Text(text),
            ),
          ],
        ),
      ),
      new Container(
        margin: const EdgeInsets.only(left: 16.0),
        child: new CircleAvatar(backgroundImage: AssetImage("assets/me.png")),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      margin: const EdgeInsets.symmetric(vertical: 10.0),
      child: new Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: this.type ? myMessage(context) : otherMessage(context),
      ),
    );
  }
}

Please notice in method here:

void response(query) async {
    _textController.clear();
    df.AuthGoogle authGoogle =
        await df.AuthGoogle(fileJson: 'assets/credential-dialogflow.json').build();
    df.Dialogflow dialogflow =
        df.Dialogflow(authGoogle: authGoogle, sessionId: '123456');
    df.DetectIntentResponse response = await dialogflow.detectIntentFromText(query, "id");
    ChatMessage message = new ChatMessage(
      text: response.queryResult.fulfillmentText,
      name: 'Munaroh',
      type: false,
    );
    setState(() {
      _messages.insert(0, message);
    });
  }

In that method, you will see AuthGoogle will load json file as credential, so you need to input your json file name. And for the sessionId, the value is free, you can input anything.

And the last, navigate your floating button in file main.dart to file chatbot.dart.

floatingActionButton: FloatingActionButton(
        child: new IconButton(icon: new Image.asset("assets/chatbot.jpg"), 
          tooltip: "Chat Me",
          onPressed: () {
            Navigator.push(context, MaterialPageRoute(builder: (context) => ChatbotDialogflow()));
          },
        ),
        onPressed: (){},
        backgroundColor: Colors.white,
      ),

Result

Finally everything is done, time to run your project and you will get the result.

flutter chatbot

Congratultaion, finally you have done create chatbot apps. You can get source code in here.

To demonstrate this article in video version, you can check this video, this video use indonesia language.

Summarize

In conclusion, create chatbot in flutter using dialogflow is no require bunch of setting.

Firstly, download your key json from correct account which connected to your project.

Second, Load your json file that already downloaded on Google Console.

By follow that rule, you can get result as you want.

Thank you for read this article, hope this help you.

In addition, if you face any trouble when you try to implement this tutorial, do not be hesitate to write your question or problem in comment below.

HAPPY SHARE!!!!

Advertisements
Share: