Здесь код
import 'package:flutter/material.dart';
//import 'package:ngts/UI/component/drawer.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dropstart/Select_Category.dart';
import 'package:grouped_buttons/grouped_buttons.dart';
import 'package:flutter_text_to_speech/flutter_text_to_speech.dart';
import 'package:speech_recognition/speech_recognition.dart';
//class Start extends StatelessWidget {
// @override
// _MyHomePageState createState() => _MyHomePageState();
//}
//class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
class Start extends StatelessWidget with WidgetsBindingObserver {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Test'),
backgroundColor: Theme.of(context).accentColor,
),
body: StreamBuilder(
//stream: Firestore.instance.
stream: Firestore.instance.collection("GK").snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
// List a = snapshot.data.documents[0].data['Option'];
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return PageView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int i) {
return QuestionOption(snapshot.data.documents[i].data['Question'],
snapshot.data.documents[i].data['Options']);
},
);
},
),
);
}
}
class QuestionOption extends StatefulWidget {
final String question;
final List option;
QuestionOption(this.question, this.option);
@override
_QuestionOptionState createState() => _QuestionOptionState();
}
class _QuestionOptionState extends State<QuestionOption> with WidgetsBindingObserver{
SpeechRecognition _speechRecognition;
bool _isAvailable = false;
bool _isListening = false;
String resultText="";
String questionAndOption;
List a = ['A', 'B', 'C', 'D'];
//SpeechToText speechToText= SpeechToText
VoiceController voiceController =
FlutterTextToSpeech.instance.voiceController();
//SpeechRecognition speechController=SpeechRecognition.instance.
@override
void initState() {
questionSpeak();
super.initState();
{
initSpeechRecognizer();
}
//initSpeechRecognizer();
// print('questionAnswer is $questionOption');
// print('Options are $options');
}
questionSpeak() {
questionAndOption = widget.question;
for (var i = 0; i < widget.option.length; i++) {
questionAndOption += 'Option ${a[i]} ${widget.option[i]}';
}
//LifecycleWatcher();
voiceController.init().then((_){
//voiceController.init().then((_) {
voiceController.speak(
questionAndOption, VoiceControllerOptions(speechRate: 0.8));
_isAvailable=true;
if (_isAvailable && !_isListening)
_speechRecognition
.listen(locale: "en_US")
.then((result) => print('$result'));
});
//_isAvailable=true;
setState(() {
});
// optionSpeak(String option) {
// voiceController.init().then(
// (_) => voiceController.speak(option, VoiceControllerOptions(delay: 3)));
// }
}
void initSpeechRecognizer() {
_speechRecognition = SpeechRecognition();
_speechRecognition.setAvailabilityHandler(
(bool result) => setState(() => _isAvailable = result),
);
_speechRecognition.setRecognitionStartedHandler(
() => setState(() => _isListening = true),
);
_speechRecognition.setRecognitionResultHandler(
(String speech) => setState(() => resultText = speech),
);
_speechRecognition.setRecognitionCompleteHandler(
() => setState(() => _isListening = false),
);
_speechRecognition.activate().then(
(result) => setState(() => _isAvailable = result),
);
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
widget.question,
style: TextStyle(
fontSize: 24.0,
),
),
),
Container(
width: MediaQuery.of(context).size.width * 0.8,
decoration: BoxDecoration(
color: Colors.cyanAccent[100],
borderRadius: BorderRadius.circular(6.0),
),
padding: EdgeInsets.symmetric(
vertical: 8.0,
horizontal: 12.0,
),
child: Text(
resultText,
style: TextStyle(fontSize: 24.0),
),
),
RadioButtonGroup(
labels: [
for (var i = 0; i < a.length; i++) '${widget.option[i]}',
],
// labels: ,
onSelected: (String selected) => print(selected),
labelStyle: TextStyle(fontSize: 18.0),
),
SizedBox(
height: 30.0,
),
RaisedButton(
onPressed: questionSpeak,
child: Text(
'Repeat',
style: TextStyle(fontSize: 18.0, color: Colors.green[900]),
),
),
Row(
children: <Widget>[
RaisedButton(
onPressed: (){},
child: Text(
'prev',
style: TextStyle(fontSize: 18.0, color: Colors.green[900]),
)
),
RaisedButton(
onPressed: (){},
child: Text(
'next',
style: TextStyle(fontSize: 18.0, color: Colors.green[900]),
),
)
],
)
],
);
}
}
, и в него я хочу добавить эти вещи
if (_isAvailable && !_isListening)
_speechRecognition
.listen(locale: "en_US")
.then((result) => print('$result'));
Я хочу сделать приложение викторины, используя речь для распознавания текста и речи, и я новичок В трепете, так что у меня много проблем для реализации вышеупомянутого. В основном, приложение должно сначала задать вопрос, и как только приложение ответит на вопрос, тогда распознавание речи должно начать принимать пользовательский ввод в виде голоса, а затем преобразовывать его в текст. с помощью _speechRecognition.listen к строке с именем resultText, а затем следует сравнить ее с приведенным сравнением, показанным в кнопке radiogroupbutton, и, если есть совпадение, он должен выполнить щелчок кнопкой мыши по радиогруппе и сохранить ответ в массиве, перейти к вопросу и т. д.
При выполнении вышеизложенного я получаю много проблем, которые Nd не может решить,