teacherman_wsls
teacherman_wsls

Reputation: 33

how to use flutter speech to text provider class

folks.....how could I use Speech To Text Provider so I can use it multiple times in multiple widgets? I read speech to text could only be started once per app session.... I know I need to use it as a provider class but I don´t know how..

I tried speech to text but It just doesn´t work for me since I need to use it in multiple widgets and I want to be able to use the callbacks "onstatus" and "onerror"

I don´t know what else to say since it is asking me to type a certain number of letters

Upvotes: 3

Views: 1140

Answers (1)

Adil Shinwari
Adil Shinwari

Reputation: 786

initialize speech to text in the root/first class.

final SpeechToText speech = SpeechToText();
late SpeechToTextProvider speechProvider;

in the initState, initialize the speechProvider and pass the speech instance to it.

speechProvider = SpeechToTextProvider(speech);

await speechProvider.initialize(); // do it in any other method and call it from initState.

in the root widget, add the ChangeNotifierProvider and pass the SpeechToTextProvider class.

ChangeNotifierProvider<SpeechToTextProvider>.value(
      value: speechProvider, 
       child: ///

now you can use speechToTextProvider anyWhere in your project.

now in order to use it anywhere in your project you have to initilaize the speechToTextProvider in the class where you want to use it.

  late SpeechToTextProvider speechToTextProvider;
  speechToTextProvider = Provider.of<SpeechToTextProvider>(context); // do it in a didChangeDependency or any other method and call it from initState.  

now in order to start listening

speechToTextProvider.listen(
        pauseFor: Duration(seconds: 5),
        localeId: 'en-us',
        listenFor: Duration(seconds: 5));
    StreamSubscription<SpeechRecognitionEvent> subscription =
        speechToTextProvider.stream.listen(
      (event) {
        // on every change it update
        if (event.eventType ==
            SpeechRecognitionEventType.partialRecognitionEvent) {
          if (mounted) {
            _setState!(
              () {
                toDisplayText =
                    speechToTextProvider.lastResult!.recognizedWords; // the textField or Text Widget Will be updated
                
              },
            );
          }
        }
        //on error
        else if (event.eventType == SpeechRecognitionEventType.errorEvent) {
          ///on error if some error occurs then close the dilog box here . or stop the listner
          }
        }
        //on done
        else if (event.eventType ==
            SpeechRecognitionEventType.finalRecognitionEvent) {
          //when the user stop speaking.
        }
      },
    );
  }

and in that way you can use it in any class or widget. You have to repeat the process of start listening in other class.

Upvotes: 6

Related Questions