AlexHartford / ibm_watson_assistant

Pure Dart package simplifying integration with IBM Watson Assistant v2 API.
MIT License
4 stars 2 forks source link

Flutter watson assistant run #6

Open sohailsk10 opened 3 years ago

sohailsk10 commented 3 years ago

can you guide me how to run a application of flutter with ibm watson assistant

AlexHartford commented 3 years ago

Make a service class that contains functions based on the API the package provides. Something like the following:

import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:ibm_watson_assistant/ibm_watson_assistant.dart';
import 'package:ibm_watson_assistant/models.dart';

class ChatbotService {
  IbmWatsonAssistant bot;
  String _sessionId;
  String get sessionId => _sessionId;

  ChatbotService() {
    final auth = IbmWatsonAssistantAuth(
      assistantId: DotEnv().env['ASSISTANT_ID'],
      url: DotEnv().env['ASSISTANT_URL'],
      apikey: DotEnv().env['API_KEY'],
    );

    this.bot = IbmWatsonAssistant(auth);
    print('Initialized Chatbot Service');
  }

  Future<String> createSession() async {
    print('creating session');
    try {
      _sessionId = await bot.createSession();
    } catch (e) {
      print('session error: $e');
      return e;
    }
    print('created session: $_sessionId');
    return _sessionId;
  }

  Future<IbmWatsonAssistantResponse> sendInput(String input) async {
    print('Sending chatbot input: $input');
    if (_sessionId == null) await createSession();
    try {
      return bot.sendInput(input, sessionId: _sessionId);
    } catch (e) {
      print('Error sending chatbot input: $input.\n$e');
      return e;
    }
  }

  Future<void> deleteSession() async {
    await bot.deleteSession(_sessionId);
    _sessionId = null;
  }
}

This makes it so you can use the API without handling things like sessionId in the UI.

In your UI you can use the service functions as you need.

If I get some time I will update the repo with a Flutter example but I cannot provide an ETA on that. It would be based on this test project: https://github.com/AlexHartford/voice_control_ui

Take a look at that and it should give you a starting point. I will leave this issue open until I add a Flutter example to this repo.