Search code examples
flutterchatbotibm-watson

Why my flutter chatbot (using ibm watson assistant) is not working?


I'm a new flutter developer. I was following this website, but my code is not working.
I think there is a problem with giving credential information in my flutter code. I want help.

watson credential details (It is a dummy workspace, that's why I'm sharing credential information)

Skill ID: 2b1bd4ed-848e-47b0-b23e-87c2e3efad15
Legacy v1 workspace URL: https://gateway.watsonplatform.net/assistant/api/v1/workspaces/2b1bd4ed-848e-47b0-b23e-87c2e3efad15/message
Service credentials name: auto-generated-apikey-41a95c12-c0f8-4752-bd47-6c52b524f399
API key: PHXjwNDFRQIaTD4j-7WvKsH3g0e5GWsQba_dyX5687lI

ibm details enter image description here

code is below:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Watson Assistant Example'),
    );
  }
}

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

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _text;
  WatsonAssistantV2Credential credential = WatsonAssistantV2Credential(
    version: '2021-07-01',
    username: 'Customer Care SampleSkill',
    apikey: 'PHXjwNDFRQIaTD4j-7WvKsH3g0e5GWsQba_dyX5687lI',
    assistantID: '2b1bd4ed-848e-47b0-b23e-87c2e3efad15',
    url: 'https://gateway.watsonplatform.net/assistant/api/v1/workspaces/2b1bd4ed-848e-47b0-b23e-87c2e3efad15/message',
  );

  WatsonAssistantApiV2 watsonAssistant;
  WatsonAssistantResponse watsonAssistantResponse;
  WatsonAssistantContext watsonAssistantContext =
      WatsonAssistantContext(context: {});

  final myController = TextEditingController();

  void _callWatsonAssistant() async {
    watsonAssistantResponse = await watsonAssistant.sendMessage(
        myController.text, watsonAssistantContext);
    setState(() {
      _text = watsonAssistantResponse.resultText;
    });
    watsonAssistantContext = watsonAssistantResponse.context;
    myController.clear();
  }

  @override
  void initState() {
    super.initState();
    watsonAssistant =
        WatsonAssistantApiV2(watsonAssistantCredential: credential);
    _callWatsonAssistant();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Watson_Assistant_V2'),
        centerTitle: true,
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.restore,
            ),
            onPressed: () {
              watsonAssistantContext.resetContext();
              setState(() {
                _text = null;
              });
            },
          )
        ],
      ),
      body: Scaffold(
        backgroundColor: Colors.white,
        body: Padding(
          padding: EdgeInsets.symmetric(horizontal: 24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              TextField(
                controller: myController,
                decoration: InputDecoration(
                  hintText: 'Your Input to the chatbot',
                  contentPadding:
                      EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(32.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide:
                        BorderSide(color: Colors.lightBlueAccent, width: 1.0),
                    borderRadius: BorderRadius.all(Radius.circular(32.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide:
                        BorderSide(color: Colors.lightBlueAccent, width: 2.0),
                    borderRadius: BorderRadius.all(Radius.circular(32.0)),
                  ),
                ),
              ),
              SizedBox(
                height: 8.0,
              ),
              Text(
                _text != null ? '$_text' : 'Watson Response Here',
                style: Theme.of(context).textTheme.display1,
              ),
              SizedBox(
                height: 24.0,
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _callWatsonAssistant,
        child: Icon(Icons.send),
      ),
    );
  }

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

Solution

  • Flutter has dependencies that needs to be added for IBM watson, please check if you have added -

    import 'package:flutter_ibm_watson/flutter_ibm_watson.dart';
    

    Here is the link for more details.

    Let me share other option using third-party tool like kommunicate

    After creating Watson assistant, integrate in Kommunicate by providing the API key, URL, and Watson Assistant ID. After that Bot will be integrated, from here you can add it to your website & mobile.

    For adding in Flutter, Kommunicate provides APP_ID which needs to be added in launch conversation. To launch the conversation you need to create a conversation object. This object is passed to the build conversation function and based on the parameters of the object the conversation is created/launched.

    Below is an example of launch conversation to add the APP_id,

    dynamic conversationObject = {
     'appId': '<APP_ID>',// The [APP_ID](https://dashboard.kommunicate.io/settings/install) obtained from kommunicate dashboard.
     };
    
    KommunicateFlutterPlugin.buildConversation(conversationObject)
        .then((clientConversationId) {
      print("Conversation builder success : " + clientConversationId.toString());
    }).catchError((error) {
      print("Conversation builder error : " + error.toString());
    });
    

    To Add Flutter SDK to your app:

    1. Add the below dependency in your pubspec.yaml file:

      kommunicate_flutter: ^1.1.6

    2. Install the package by running this command as flutter pub get

    3. Import kommunicate_flutter in your .dart file to use the methods from Kommunicate:

      import 'package:kommunicate_flutter/kommunicate_flutter.dart';

    4. For iOS, navigate to your App/iOS directory from the terminal and run the below command:

    pod install

     platform :ios, '10.0'
     use_frameworks!
    

    Please find the attached docs & links for reference.

    Check out the blog for more details

    A guide for installing flutter app