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.