speechService static method
Implementation
static String speechService() {
return '''
import 'package:flutter/foundation.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
/// Simple wrapper around speech_to_text.
///
/// Usage:
/// final speech = SpeechService();
/// await speech.init();
/// await speech.startListening(onResult: (text) { /* use text */ });
/// await speech.stopListening();
class SpeechService {
final stt.SpeechToText _speech = stt.SpeechToText();
bool _available = false;
bool get isAvailable => _available;
bool get isListening => _speech.isListening;
Future<bool> init() async {
_available = await _speech.initialize(
onStatus: (status) {
if (kDebugMode) {
debugPrint('Speech status: \$status');
}
},
onError: (error) {
if (kDebugMode) {
debugPrint('Speech error: \$error');
}
},
);
return _available;
}
Future<void> startListening({
required ValueChanged<String> onResult,
String localeId = 'en_US',
}) async {
if (!_available) {
final ok = await init();
if (!ok) return;
}
await _speech.listen(
onResult: (result) => onResult(result.recognizedWords),
localeId: localeId,
);
}
Future<void> stopListening() async {
await _speech.stop();
}
Future<void> cancel() async {
await _speech.cancel();
}
}
''';
}