Как отобразить расширенное сообщение, такое как Google Card-Assistant-output Basic Card, в приложении Flutter - PullRequest
0 голосов
/ 16 мая 2019

Я создал чат-бота с диалоговым потоком и (https://github.com/diegodalbosco/flutter_dialogflow) это нормально работает с простым текстовым ответом.

Затем, когда я добавлю Google Assistant в ответ (Намерение), например: ответы с помощью Basic Card.

Когда я запускаю это приложение на телефоне Android, я могу писать нормально и видеть нормальные ответы. Но когда я пытаюсь написать «Запрос» или «Намерение» что-то, чтобы вызвать ответ Основной карты Google Assistant, остановка приложения и ошибка.

Может ли кто-нибудь помочь?

Я считаю, что ответ Google Assistant поддерживается Flutter?

Может ли кто-нибудь объяснить, как установить, отображать расширенное сообщение ответа Google Assistant, как Basic Card, в приложении флаттера?

ThankYou

Я сказал: "

and
"ChatMessage message = new ChatMessage(
      text: response.queryResult.fulfillmentText
 ?? new df.BasicCard(),"
and
"new Container(
              margin: const EdgeInsets.only(top: 5.0),
              child: new Text(text?? new df.BasicCard()),
            ),

"

ищет документы по:

https://pub.dev/documentation/flutter_dialogflow_v2/latest/model_query_result/QueryResult/fulfillmentMessages.html для выполнения сообщения свойства

- https://pub.dev/documentation/flutter_dialogflow_v2/latest/model_message_basic_card/BasicCard-class.html для BasicCard

- https://pub.dev/documentation/flutter_dialogflow_v2/latest/model_query_result/QueryResult-class.html для класса QueryResult

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

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

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

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

  final String title;
  final List<df.BasicCard> fulfillmentMessages = <df.BasicCard>[];


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

class _MyHomePageState extends State<MyHomePage> {
  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/project-id.json').build();
    df.Dialogflow dialogflow =
        df.Dialogflow(authGoogle: authGoogle, sessionId: '123456');
    df.DetectIntentResponse response = await dialogflow.detectIntent(query);
    ChatMessage message = new ChatMessage(
      text: response.queryResult.fulfillmentText
 ?? new df.BasicCard()
,
      name: 'Bot',
      type: false,
    );
    setState(() {
      _messages.insert(0, message);
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Dialogflow V2'),
      ),
      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(child: new Image.asset('img/placeholder.png')),
      ),
      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?? new df.BasicCard()),
            ),
          ],
        ),
      ),
    ];
  }

  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(child: new Text(this.name[0])),
      ),
    ];
  }

  @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),
      ),
    );
  }
}

Я ожидаю, что результат будет выглядеть так: когда я спрашиваю предустановленное намерение для BasicCard, приложение показывает ответ с BasicCard, но фактический вывод ошибка: " E / flutter (4203): [ОШИБКА: flutter / lib / ui / ui_dart_state.cc (148)] Необработанное исключение: NoSuchMethodError: Метод '[]' был вызван для нуля. E / трепетание (4203) E / flutter (4203): пробный вызов: "

и нет ответа в приложении чата флаттера.

1 Ответ

0 голосов
/ 20 мая 2019

Для действий Google Assistant вам необходимо использовать одну из наших клиентских библиотек (Node.js или Java).Библиотека Dialogflow предназначена для поддержки других платформ, но не только для Google Assistant (некоторые вещи могут работать кросс-платформенными, а другие, как карты, - нет).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...