Display and edit text into TextFormField using voice (Flutter Speech to text)

Viewed 152

I am working on Flutter speech to text. The scenery is user can give their comment using voice. While they give input for comment by their voice they may edit the comment field and enter some text(given by their voice) into any position. Like, I give input using my voice and want to enter some words on the first or middle or any place where I think I've to add some words for completing my comments. I am using speech_to_text: ^5.2.0. Following are the code sample. Here, I just came to display the text into TextFormField. The value remove when I re-enter my voice. But what I need the value have to be in TextFormField and I can edit it any position of the given word that I think I've to input here.

class MyApp extends StatefulWidget {

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String text = 'Hi';
  bool isListening = false;
  final _textEditingController  = TextEditingController();
  late stt.SpeechToText _speech;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          body: SingleChildScrollView(
            child: Column(
              children: [
                TextFormField(
                  controller: _textEditingController,
                ),
                Text(text),
              ],
            )
          ),
          floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
          floatingActionButton: AvatarGlow(
            animate: isListening,
            endRadius: 150,
            glowColor: Theme.of(context).primaryColor,
            child: FloatingActionButton(
              onPressed: toggleRecording,
              child: Icon(isLintening ? Icons.mic : Icons.mic_none),
        ),
          ),
      ),
    ));
  }

  Future toggleRecording() => SpechApi.toggleRecording(
      onResult: (text) => setState(() {
        this.text = text;
        _textEditingController.text = text;
      }),
      onListening: (isLintening) {
        setState(() => this.isListening = isListening);

        if(!isListening) {
          Future.delayed(Duration(seconds: 1), () {
            // Utils.scanText(text);
            _textEditingController.text = text;
          });
        }
      });
  void onListen() async {
    bool available = await _speech.initialize(
        onStatus: (val) => print('onStatus: $val'),
        onError: (val) => print('onError: $val'));

    if (!isListening) {
      if (available) {
        setState(() {
          isLintening = false;
          _speech.listen(
            onResult: (val) => setState(() {
              _textEditingController.text = text;
            }),
          );
        });
      }
    } else {
      setState(() {
        isLintening = false;
        _speech.stop();
      });
    }
  }
}
0 Answers
Related