voice search

pull/159/head
Sultan Khan 6 years ago
parent dca7cf9b05
commit 6eb2da3770

@ -2,9 +2,9 @@ const MAX_SMALL_SCREEN = 660;
const ONLY_NUMBERS = "[0-9]"; const ONLY_NUMBERS = "[0-9]";
const ONLY_LETTERS = "[a-zA-Z &'\"]"; const ONLY_LETTERS = "[a-zA-Z &'\"]";
const ONLY_DATE = "[0-9/]"; const ONLY_DATE = "[0-9/]";
//const BASE_URL = 'https://hmgwebservices.com/Services/'; const BASE_URL = 'https://hmgwebservices.com/Services/';
const BASE_URL = 'https://uat.hmgwebservices.com/'; //const BASE_URL = 'https://uat.hmgwebservices.com/';
const PHARMACY_ITEMS_URL = "Services/Lists.svc/REST/GetPharmcyItems_Region"; const PHARMACY_ITEMS_URL = "Services/Lists.svc/REST/GetPharmcyItems_Region_enh";
const PHARMACY_LIST_URL = "Services/Patients.svc/REST/GetPharmcyList"; const PHARMACY_LIST_URL = "Services/Patients.svc/REST/GetPharmcyList";
const PATIENT_PROGRESS_NOTE_URL = const PATIENT_PROGRESS_NOTE_URL =
"Services/DoctorApplication.svc/REST/GetProgressNoteForInPatient"; "Services/DoctorApplication.svc/REST/GetProgressNoteForInPatient";
@ -126,7 +126,7 @@ const TRANSACTION_NO = 0;
const LANGUAGE_ID = 2; const LANGUAGE_ID = 2;
const STAMP = '2020-04-27T12:17:17.721Z'; const STAMP = '2020-04-27T12:17:17.721Z';
const IP_ADDRESS = '11.11.11.11'; const IP_ADDRESS = '11.11.11.11';
const VERSION_ID = 1.2; const VERSION_ID = 5.3;
const CHANNEL = 9; const CHANNEL = 9;
const SESSION_ID = 'BlUSkYymTt'; const SESSION_ID = 'BlUSkYymTt';
const IS_LOGIN_FOR_DOCTOR_APP = true; const IS_LOGIN_FOR_DOCTOR_APP = true;

@ -1,4 +1,3 @@
/* /*
*@author: Ibrahim Albitar *@author: Ibrahim Albitar
*@Date:27/4/2020 *@Date:27/4/2020
@ -8,8 +7,6 @@
*/ */
class PharmaciesListRequestModel { class PharmaciesListRequestModel {
int itemID; int itemID;
int languageID; int languageID;
String stamp; String stamp;
@ -23,13 +20,13 @@ class PharmaciesListRequestModel {
int channel; int channel;
PharmaciesListRequestModel( PharmaciesListRequestModel(
{this.itemID , {this.itemID,
this.patientTypeID = 1, this.patientTypeID = 1,
this.languageID = 2, this.languageID = 2,
this.stamp = '2020-04-23T21:01:21.492Z', this.stamp = '2020-04-23T21:01:21.492Z',
this.ipAdress = '11.11.11.11', this.ipAdress = '11.11.11.11',
this.versionID = 1.2, this.versionID = 5.3,
this.tokenID , this.tokenID,
this.sessionID = 'e29zoooEJ4', this.sessionID = 'e29zoooEJ4',
this.isLoginForDoctorApp = true, this.isLoginForDoctorApp = true,
this.channel = 9, this.channel = 9,

@ -6,12 +6,11 @@
*@desc: *@desc:
*/ */
class PharmaciesItemsRequestModel { class PharmaciesItemsRequestModel {
String pHRItemName; String pHRItemName;
int pageIndex = 0; int pageIndex = 0;
int pageSize = 20; int pageSize = 20;
double versionID = 5.2; double versionID = 5.3;
int channel = 3; int channel = 3;
int languageID = 2; int languageID = 2;
String iPAdress = "10.20.10.20"; String iPAdress = "10.20.10.20";
@ -25,7 +24,7 @@ class PharmaciesItemsRequestModel {
{this.pHRItemName, {this.pHRItemName,
this.pageIndex = 0, this.pageIndex = 0,
this.pageSize = 20, this.pageSize = 20,
this.versionID = 5.2, this.versionID = 5.3,
this.channel = 3, this.channel = 3,
this.languageID = 2, this.languageID = 2,
this.iPAdress = "10.20.10.20", this.iPAdress = "10.20.10.20",

@ -15,16 +15,15 @@ class MedicineProvider with ChangeNotifier {
String errorMsg = ''; String errorMsg = '';
PharmaciesItemsRequestModel _itemsRequestModel = PharmaciesItemsRequestModel _itemsRequestModel =
PharmaciesItemsRequestModel(); PharmaciesItemsRequestModel();
PharmaciesListRequestModel _listRequestModel = PharmaciesListRequestModel(); PharmaciesListRequestModel _listRequestModel = PharmaciesListRequestModel();
clearPharmacyItemsList() {
clearPharmacyItemsList(){
pharmacyItemsList.clear(); pharmacyItemsList.clear();
notifyListeners(); notifyListeners();
} }
getMedicineItem(String itemName) async { getMedicineItem(String itemName) async {
_itemsRequestModel.pHRItemName = itemName; _itemsRequestModel.pHRItemName = itemName;
resetDefaultValues(); resetDefaultValues();
pharmacyItemsList.clear(); pharmacyItemsList.clear();
@ -32,37 +31,37 @@ class MedicineProvider with ChangeNotifier {
try { try {
await BaseAppClient.post(PHARMACY_ITEMS_URL, await BaseAppClient.post(PHARMACY_ITEMS_URL,
onSuccess: (dynamic response, int statusCode) { onSuccess: (dynamic response, int statusCode) {
pharmacyItemsList = response['ListPharmcy_Region']; pharmacyItemsList = response['ListPharmcy_Region_enh'];
hasError = false; hasError = false;
isFinished = true; isFinished = true;
errorMsg = "Done"; errorMsg = "Done";
}, onFailure: (String error, int statusCode) { }, onFailure: (String error, int statusCode) {
isFinished = true; isFinished = true;
hasError = true; hasError = true;
errorMsg = error; errorMsg = error;
}, body: _itemsRequestModel.toJson()); }, body: _itemsRequestModel.toJson());
notifyListeners(); notifyListeners();
} catch (error) { } catch (error) {
throw error; throw error;
} }
} }
getPharmaciesList(int itemId) async { getPharmaciesList(int itemId) async {
resetDefaultValues(); resetDefaultValues();
try { try {
_listRequestModel.itemID = itemId; _listRequestModel.itemID = itemId;
isFinished = true; isFinished = true;
await BaseAppClient.post(PHARMACY_LIST_URL, await BaseAppClient.post(PHARMACY_LIST_URL,
onSuccess: (dynamic response, int statusCode) { onSuccess: (dynamic response, int statusCode) {
pharmaciesList = response['PharmList']; pharmaciesList = response['PharmList'];
hasError = false; hasError = false;
isFinished = true; isFinished = true;
errorMsg = "Done"; errorMsg = "Done";
}, onFailure: (String error, int statusCode) { }, onFailure: (String error, int statusCode) {
isFinished = true; isFinished = true;
hasError = true; hasError = true;
errorMsg = error; errorMsg = error;
}, body: _listRequestModel.toJson()); }, body: _listRequestModel.toJson());
notifyListeners(); notifyListeners();
} catch (error) { } catch (error) {
throw error; throw error;

@ -13,8 +13,14 @@ import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/dr_app_circular_progress_Indeicator.dart'; import 'package:doctor_app_flutter/widgets/shared/dr_app_circular_progress_Indeicator.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../../util/extenstions.dart'; import '../../util/extenstions.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart'; import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:speech_to_text/speech_recognition_error.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'dart:math';
DrAppSharedPreferances sharedPref = DrAppSharedPreferances(); DrAppSharedPreferances sharedPref = DrAppSharedPreferances();
@ -30,20 +36,55 @@ class _MedicineSearchState extends State<MedicineSearchScreen> {
var data; var data;
final myController = TextEditingController(); final myController = TextEditingController();
Helpers helpers = new Helpers(); Helpers helpers = new Helpers();
bool _hasSpeech = false;
MedicineProvider _medicineProvider; MedicineProvider _medicineProvider;
String _currentLocaleId = "";
bool _isInit = true; bool _isInit = true;
final SpeechToText speech = SpeechToText();
String lastStatus = '';
// String lastWords;
List<LocaleName> _localeNames = [];
String lastError;
double level = 0.0;
double minSoundLevel = 50000;
double maxSoundLevel = -50000;
String reconizedWord;
@override @override
void didChangeDependencies() { void didChangeDependencies() {
super.didChangeDependencies(); super.didChangeDependencies();
if (_isInit) { if (_isInit) {
_medicineProvider = Provider.of<MedicineProvider>(context); _medicineProvider = Provider.of<MedicineProvider>(context);
requestPermissions();
initSpeechState();
} }
_isInit = false; _isInit = false;
} }
void requestPermissions() async {
Map<Permission, PermissionStatus> statuses = await [
Permission.microphone,
].request();
}
Future<void> initSpeechState() async {
bool hasSpeech = await speech.initialize(
onError: errorListener, onStatus: statusListener);
// if (hasSpeech) {
// _localeNames = await speech.locales();
// var systemLocale = await speech.systemLocale();
_currentLocaleId = TranslationBase.of(context).locale.languageCode == 'en'
? 'en-GB'
: 'ar-SA'; // systemLocale.localeId;
// }
if (!mounted) return;
setState(() {
_hasSpeech = hasSpeech;
});
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return AppScaffold( return AppScaffold(
@ -60,10 +101,22 @@ class _MedicineSearchState extends State<MedicineSearchScreen> {
hintText: TranslationBase.of(context).searchMedicineNameHere, hintText: TranslationBase.of(context).searchMedicineNameHere,
controller: myController, controller: myController,
onSaved: (value) {}, onSaved: (value) {},
onFieldSubmitted: (value){ onFieldSubmitted: (value) {
searchMedicine(context); searchMedicine(context);
}, },
textInputAction: TextInputAction.search, textInputAction: TextInputAction.search,
prefix: IconButton(
icon: Icon(Icons.mic),
color:
lastStatus == 'listening' ? Colors.red : Colors.grey,
onPressed: () {
myController.text = '';
setState(() {
lastStatus = 'listening';
});
startVoiceSearch();
}),
inputFormatter: ONLY_LETTERS), inputFormatter: ONLY_LETTERS),
), ),
Container( Container(
@ -92,7 +145,10 @@ class _MedicineSearchState extends State<MedicineSearchScreen> {
children: <Widget>[ children: <Widget>[
AppText( AppText(
TranslationBase.of(context).youCanFind + TranslationBase.of(context).youCanFind +
(_medicineProvider.pharmacyItemsList == null ? "0" : _medicineProvider.pharmacyItemsList.length.toString()) + (_medicineProvider.pharmacyItemsList == null
? "0"
: _medicineProvider.pharmacyItemsList.length
.toString()) +
TranslationBase.of(context).itemsInSearch, TranslationBase.of(context).itemsInSearch,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
margin: 5, margin: 5,
@ -116,12 +172,19 @@ class _MedicineSearchState extends State<MedicineSearchScreen> {
: ListView.builder( : ListView.builder(
scrollDirection: Axis.vertical, scrollDirection: Axis.vertical,
shrinkWrap: true, shrinkWrap: true,
itemCount: _medicineProvider.pharmacyItemsList == null ? 0 : _medicineProvider.pharmacyItemsList.length, itemCount: _medicineProvider.pharmacyItemsList ==
null
? 0
: _medicineProvider.pharmacyItemsList.length,
itemBuilder: (BuildContext context, int index) { itemBuilder: (BuildContext context, int index) {
return InkWell( return InkWell(
child: MedicineItemWidget( child: MedicineItemWidget(
label: _medicineProvider.pharmacyItemsList[index]["ItemDescription"], label:
url: _medicineProvider.pharmacyItemsList[index]["ProductImageBase64"], _medicineProvider.pharmacyItemsList[index]
["ItemDescription"],
url:
_medicineProvider.pharmacyItemsList[index]
["ImageThumbUrl"],
), ),
onTap: () { onTap: () {
Navigator.push( Navigator.push(
@ -129,9 +192,12 @@ class _MedicineSearchState extends State<MedicineSearchScreen> {
MaterialPageRoute( MaterialPageRoute(
builder: (context) => builder: (context) =>
PharmaciesListScreen( PharmaciesListScreen(
itemID: _medicineProvider.pharmacyItemsList[index]["ItemID"], itemID: _medicineProvider
url: _medicineProvider.pharmacyItemsList[index] .pharmacyItemsList[index]
["ProductImageBase64"]), ["ItemID"],
url: _medicineProvider
.pharmacyItemsList[index]
["ProductImageBase64"]),
), ),
); );
}, },
@ -153,4 +219,62 @@ class _MedicineSearchState extends State<MedicineSearchScreen> {
} }
_medicineProvider.getMedicineItem(myController.text); _medicineProvider.getMedicineItem(myController.text);
} }
startVoiceSearch() {
// lastWords = "";
lastError = "";
speech.listen(
onResult: resultListener,
listenFor: Duration(seconds: 10),
localeId: _currentLocaleId,
onSoundLevelChange: soundLevelListener,
cancelOnError: true,
partialResults: true,
onDevice: true,
listenMode: ListenMode.confirmation);
setState(() {});
}
void resultListener(SpeechRecognitionResult result) {
setState(() {
// lastWords = "${result.recognizedWords} - ${result.finalResult}";
reconizedWord = result.recognizedWords;
lastStatus = '';
myController.text = reconizedWord;
Future.delayed(const Duration(seconds: 2), () {
searchMedicine(context);
});
});
}
void errorListener(SpeechRecognitionError error) {
// print("Received error status: $error, listening: ${speech.isListening}");
setState(() {
lastError = "${error.errorMsg} - ${error.permanent}";
});
}
void statusListener(String status) {
// print(
// "Received listener status: $status, listening: ${speech.isListening}");
setState(() {
lastStatus = status;
});
}
// _switchLang(selectedVal) {
// setState(() {
// _currentLocaleId = selectedVal;
// });
// print(selectedVal);
// }
void soundLevelListener(double level) {
minSoundLevel = min(minSoundLevel, level);
maxSoundLevel = max(maxSoundLevel, level);
// print("sound level $level: $minSoundLevel - $maxSoundLevel ");
setState(() {
this.level = level;
});
}
} }

@ -273,7 +273,7 @@ class _LoginFormState extends State<LoginForm> {
"ProjectName": "", "ProjectName": "",
"DoctorImageURL": "UNKNOWN", "DoctorImageURL": "UNKNOWN",
"LogInTokenID": preRes['LogInTokenID'], "LogInTokenID": preRes['LogInTokenID'],
"VersionID": 1.2 "VersionID": 5.3
}; };
authProv.insertDeviceImei(imeiInfo).then((res) { authProv.insertDeviceImei(imeiInfo).then((res) {
if (res['MessageStatus'] == 1) { if (res['MessageStatus'] == 1) {

@ -47,8 +47,8 @@ class _MedicineItemWidgetState extends State<MedicineItemWidget> {
width: 39, width: 39,
child: ClipRRect( child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(7)), borderRadius: BorderRadius.all(Radius.circular(7)),
child: Image.memory( child: Image.network(
dataFromBase64String(widget.url), widget.url,
height: SizeConfig.imageSizeMultiplier * 15, height: SizeConfig.imageSizeMultiplier * 15,
width: SizeConfig.imageSizeMultiplier * 15, width: SizeConfig.imageSizeMultiplier * 15,
fit: BoxFit.cover, fit: BoxFit.cover,

@ -8,61 +8,63 @@ import 'package:flutter/services.dart';
// DESCRIPTION : Custom Text Form Field for app. // DESCRIPTION : Custom Text Form Field for app.
class AppTextFormField extends FormField<String> { class AppTextFormField extends FormField<String> {
AppTextFormField(
AppTextFormField({ {FormFieldSetter<String> onSaved,
FormFieldSetter<String> onSaved, String inputFormatter,
String inputFormatter, FormFieldValidator<String> validator,
FormFieldValidator<String> validator, ValueChanged<String> onChanged,
ValueChanged<String> onChanged, GestureTapCallback onTap,
GestureTapCallback onTap, TextEditingController controller,
TextEditingController controller, bool autovalidate = true,
bool autovalidate = true, TextInputType textInputType,
TextInputType textInputType, String hintText,
String hintText, FocusNode focusNode,
FocusNode focusNode, TextInputAction textInputAction,
TextInputAction textInputAction, ValueChanged<String> onFieldSubmitted,
ValueChanged<String> onFieldSubmitted, IconButton prefix})
}) : super( : super(
onSaved: onSaved, onSaved: onSaved,
validator: validator, validator: validator,
autovalidate: autovalidate, autovalidate: autovalidate,
builder: (FormFieldState<String> state) { builder: (FormFieldState<String> state) {
return Column( return Column(
children: <Widget>[ children: <Widget>[
TextFormField( TextFormField(
focusNode: focusNode, focusNode: focusNode,
keyboardType: textInputType, keyboardType: textInputType,
inputFormatters: [WhitelistingTextInputFormatter(RegExp(inputFormatter)),], inputFormatters: [
onChanged: onChanged?? (value){ WhitelistingTextInputFormatter(RegExp(inputFormatter)),
state.didChange(value); ],
}, onChanged: onChanged ??
textInputAction: textInputAction, (value) {
onFieldSubmitted: onFieldSubmitted, state.didChange(value);
decoration: InputDecoration( },
hintText: hintText, textInputAction: textInputAction,
hintStyle: TextStyle(fontSize: SizeConfig.textMultiplier * 2), onFieldSubmitted: onFieldSubmitted,
enabledBorder: OutlineInputBorder( decoration: InputDecoration(
borderRadius: BorderRadius.all(Radius.circular(10)), hintText: hintText,
borderSide: BorderSide(color: Color(0xff707070)), suffixIcon: prefix,
), hintStyle:
focusedBorder: OutlineInputBorder( TextStyle(fontSize: SizeConfig.textMultiplier * 2),
borderRadius: BorderRadius.all(Radius.circular(10)), enabledBorder: OutlineInputBorder(
) borderRadius: BorderRadius.all(Radius.circular(10)),
//BorderRadius.all(Radius.circular(20)); borderSide: BorderSide(color: Color(0xff707070)),
), ),
onTap: onTap, focusedBorder: OutlineInputBorder(
controller: controller, borderRadius: BorderRadius.all(Radius.circular(10)),
), )
state.hasError? //BorderRadius.all(Radius.circular(20));
Text( ),
state.errorText, onTap: onTap,
style: TextStyle( controller: controller,
color: Colors.red ),
), state.hasError
) : ? Text(
Container() state.errorText,
], style: TextStyle(color: Colors.red),
); )
} : Container()
); ],
);
});
} }

@ -31,7 +31,7 @@ android {
main.java.srcDirs += 'src/main/kotlin' main.java.srcDirs += 'src/main/kotlin'
} }
defaultConfig { defaultConfig {
minSdkVersion 21 minSdkVersion 18
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
} }
lintOptions { lintOptions {

@ -39,7 +39,7 @@ android {
defaultConfig { defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.csdcorp.speech_to_text_example" applicationId "com.csdcorp.speech_to_text_example"
minSdkVersion 21 minSdkVersion 18
targetSdkVersion 28 targetSdkVersion 28
versionCode flutterVersionCode.toInteger() versionCode flutterVersionCode.toInteger()
versionName flutterVersionName versionName flutterVersionName

@ -120,12 +120,13 @@ class SpeechToTextProvider extends ChangeNotifier {
_lastResult = null; _lastResult = null;
if (soundLevel) { if (soundLevel) {
_speechToText.listen( _speechToText.listen(
partialResults: partialResults, partialResults: partialResults,
listenFor: listenFor, listenFor: listenFor,
pauseFor: pauseFor, pauseFor: pauseFor,
cancelOnError: true, cancelOnError: true,
onResult: _onListenResult, onResult: _onListenResult,
onSoundLevelChange: _onSoundLevelChange); // onSoundLevelChange: _onSoundLevelChange);
);
} else { } else {
_speechToText.listen( _speechToText.listen(
partialResults: partialResults, partialResults: partialResults,
@ -187,14 +188,14 @@ class SpeechToTextProvider extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
void _onSoundLevelChange(double level) { // void _onSoundLevelChange(double level) {
_lastLevel = level; // _lastLevel = level;
_recognitionController.add(SpeechRecognitionEvent( // _recognitionController.add(SpeechRecognitionEvent(
SpeechRecognitionEventType.soundLevelChangeEvent, // SpeechRecognitionEventType.soundLevelChangeEvent,
null, // null,
null, // null,
null, // null,
level)); // level));
notifyListeners(); // notifyListeners();
} // }
} }

Loading…
Cancel
Save