【问题标题】:Add text to TextField from an outside source从外部来源向 TextField 添加文本
【发布时间】:2019-10-26 17:42:54
【问题描述】:

我在文本字段中添加了语音识别,它可以工作,但我无法将文本添加到文本字段,有没有办法做到这一点。

文本字段如下所示:

  Widget _buildDescriptionTextField(productBloc) {
    return StreamBuilder<Object>(
        stream: productBloc.messageStream,
        builder: (context, snapshot) {
          return TextField(
            maxLines: 3,
            controller: _controllerMessage,
            onChanged: productBloc.messageSink,
            decoration: InputDecoration(
              labelText: allTranslations.text(StringConstant.description),
              errorText: snapshot.error,
              suffixIcon: IconButton(icon: Icon(Icons.mic), onPressed: () {
                if (_isAvailable && !_isListening)
                  _speechRecognition
                      .listen(locale: "en_US")
                      .then((result) => print('$result'));
              },
              ),
            ),
          );
        }
    );
  }

我有一个 steam-builder 来手动管理添加的文本,如果此页面用于编辑,我有一个控制器,然后作为 suffixsIcon 的 iconButton 启动语音识别。当我在文本小部件之外添加结果文本时,它可以工作,但我需要在 texField 中使用它。

【问题讨论】:

    标签: flutter speech-recognition textfield flutter-layout


    【解决方案1】:

    所以我所做的只是使用文档中的 _speechRecognition.setRecognitionResultHandler 为 textField 的控制器设置一个新值,如下所示:

        _speechRecognition.setRecognitionResultHandler(
              (String speech) => setState(() {
                _controllerMessage = new TextEditingController(text: resultText = speech);
              })
        );
    

    textField 保持原样,请参阅问题。

    【讨论】:

      【解决方案2】:

      您需要使用TextEditingController 属性。我假设您将其中之一声明为_controllerMessage

      要为您的 TextField 设置新值并将光标保留在最后 - 使用类似于文档中的示例的内容。

      例如

      _speechRecognition
        .listen(locale: "en_US")
        .then(_onResult);
      
      // ...
      
      void _onResult(String result) {
        setState(() {
          _controllerMessage.value = _controllerMessage.value.copyWith(
            text: result,
            selection: TextSelection(baseOffset: result.length, extentOffset: result.length),
            composing: TextRange.empty,
          );
        });
      }
      

      如果这有帮助,请告诉我。

      【讨论】:

      • 不幸的是这不起作用,我用它做了一个简单的应用程序但仍然不起作用,还有其他想法吗?
      • @key 请查看我的更新答案。我完全忽略了“结果”变量的使用。让我们看看它现在是否有效。
      • 你能再看看吗,在更改 text.length 后,我设法删除了所有错误,但它仍然不起作用
      • 我使用文档中的方法解决了它。但非常感谢您的帮助。我投票赞成你的答案。看我的回答
      【解决方案3】:

      只是这样做应该行不通?

      setState(() => _controllerMessage.text = result)
      

      【讨论】:

        猜你喜欢
        • 2012-11-26
        • 2011-12-31
        • 1970-01-01
        • 2023-04-08
        • 2020-09-28
        • 2014-12-27
        • 1970-01-01
        • 2017-09-08
        • 1970-01-01
        相关资源
        最近更新 更多