Flutter QR-code scanner rapidly scan issue, how to control the second scan? - flutter

Does anyone know how to adjust the QR code scanner speed? since the second scan is so quick,
source example is down below, you can download it add and run it in your Flutter project to test!
What are the differenceis are in the controller.scannedDataStream.listen() function. I posted down below:
Barcode? result;
var qrText = "";
bool isValid = false;
bool isExpired = false;
QRViewController? controller;
controller.scannedDataStream.listen((scanData) async {
log(scanData.code);
if (!scanData.code.contains('?key=')) {
setState(() {
qrText = "This is not a correct code";
isValid = false;
});
} else {
var key_hash = scanData.code.split('?key=');
log('hash: ' + key_hash[1]);
await decrypt(key_hash[1]).then((String result) async {
if (result == "") {
log('result: ' + result);
await controller.stopCamera();
setState(() {
qrText = result;
isValid = true;
isExpired = true;
});
}
else {
log('result: ' + result);
await controller.pauseCamera();
await controller.stopCamera();
setState(() {
qrText = result;
isValid = true;
isExpired = false;
});
}
});
}
});
https://pub.dev/packages/qr_code_scanner/example

Related

Pull to refresh package in flutter for pagination purpose

Hello Readers I am new in flutter and i want to do pagination, for pagination I am using one package which name is "pull to refersh".
Problems :
I have total 6 post and per page limits are 3.
1)When I reached at the end of list then api will call and set current page variable value is 2 and it will load all data of page 2 as a new list, but i want to merge page 2 data into same list... (Pagination like facebook instagram etc).
2)My another problem is when i pull for refersh, page is refersh perfectly and it will go to the first page but problem is, when i again go at the end of list it shows me no more data(which means page 2 api is not working)
I have one condition like if else:- "hasNextPage" this variable getting from api and the response is 1 or 2, if response is 1 then there further page after current page and if is 0 then there is no page after current page.
I am posting my code and api link also can you please help me.
Method for get data from API
int currentPage = 1;
bool isRefersh = false;
final RefreshController refreshController = RefreshController();
Future<UserPost> getUserPost() async {
var url =
"LINK=$currentPage";
var response = await http.get(Uri.parse(url));
var jsondata = jsonDecode(response.body.toString());
var _apiData = UserPost.fromJson(jsondata);
if (response.statusCode == 200) {
print("******getUserPost API");
print("current page****$currentPage");
print("hasnext page ${_apiData.hasNextPage}");
print(jsondata);
if(isRefersh == true){
setState((){
//currentPage = 1;
isRefersh = false;
});
refreshController.refreshCompleted();
return UserPost.fromJson(jsondata);
}
else{
print("//////////////// has next page");
print(_apiData.hasNextPage.toString());
if(_apiData.hasNextPage == 0){
refreshController.loadNoData();
return UserPost.fromJson(jsondata);
}else{
}
return UserPost.fromJson(jsondata);
}
} else {
return UserPost.fromJson(jsondata);
}
}
Method for pull to Refersh
onRefresh: () async{
await Future.delayed(Duration(milliseconds: 1000));
setState(() {
isRefersh = true;
currentPage = 1;
});
},
Method for Pagination
onLoading: () async {
if(snapshot.data!.hasNextPage == 0){
refreshController.loadNoData();
}else{
setState(() {
currentPage++;
});
await Future.delayed(Duration(milliseconds: 1000));
refreshController.loadComplete();
}
},
I Hope it's help you
try this way :-
final RefreshController refreshController =
RefreshController(initialRefresh: true);
Future<bool> getPassengerData({bool isRefresh = false}) async {
if (isRefresh) {
currentPage = 1;
} else {
if (currentPage >= totalPages) {
refreshController.loadNoData();
return false;
}
}
final Uri uri = Uri.parse(
"api url=$currentPage&size=10");
final response = await http.get(uri);
if (response.statusCode == 200) {
final result = passengersDataFromJson(response.body);
if (isRefresh) {
passengers = result.data;
}else{
passengers.addAll(result.data);
}
currentPage++;
totalPages = result.totalPages;
print(response.body);
setState(() {});
return true;
} else {
return false;
}
}
Method for pull to Refersh
onRefresh: () async {
final result = await getPassengerData(isRefresh: true);
if (result) {
refreshController.refreshCompleted();
} else {
refreshController.refreshFailed();
}
},
Method for onLoading:
onLoading: () async {
final result = await getPassengerData();
if (result) {
refreshController.loadComplete();
} else {
refreshController.loadFailed();
}
},
Try this way.
when you get the response in second page just create new list with previous list.
i.e var newData = [...?dummyData.data, ...?_apiData.data];
than return this same list.
UserPostModel dummyData = UserPostModel();
Future<UserPostModel> getUserPost() async {
var url =
"*****?page=$currentPage";
var response = await http.get(Uri.parse(url));
var jsondata = jsonDecode(response.body.toString());
var _apiData = UserPostModel.fromJson(jsondata);
var newData = [...?dummyData.data, ...?_apiData.data];
//totalPage = _apiData.totalPages as int?;
if (response.statusCode == 200) {
if (isRefersh == true) {
setState(() {
isRefersh = false;
});
refreshController.refreshCompleted();
} else {
if (_apiData.hasNextPage == 0) {
refreshController.loadNoData();
} else {
refreshController.loadComplete();
}
}
dummyData.data = newData;
return dummyData;
} else {
return dummyData;
}
}

bool value always returns true flutter

I am having trouble with the bool value. My bool value returns true only.
I have five buttons which set the state for the bool and time for fasting.
ElevatedButton(
onPressed: () async {
final SharedPreferences prefs = await _prefs;
playLocalAsset(0);
if((isFasting = true) && (widget.isFasting = true)) {
showError();
removeHours(fastDurs);
setState(() {
isFasting = false;
widget.isFasting = false;
});
//showAlerts();
} else {
setState(() {
isFasting = true;
widget.isFasting = true;
fastDuration = 16;
sixteen = 16;
eighteen = null;
twenty= null;
twentytwo = null;
twentyfour = null;
widget.fastDuration= 16;
endTime = startTime.add(Duration(hours: fastDuration!));
endTimeS = DateFormat('y/M/d, hh:mma').format(endTime);
_textLine = prefs
.setString('formattedDate', endTimeS)
.then((value) => (prefs
.getString('formattedDate') ??
Languages.of(context)!.setYourFastTime +'\n'+ startTimeS));
textDate = prefs.setString('eatTime', Languages.of(context)!.youWillEatAt)
.then((value) => (prefs.getString('eatTime') ?? ''));
showMessage(Languages.of(context)!.yourFastTimeIsSet);
updateHours(16);
});
}
},
child: Text('16:8', style: Constants.textTitleStyle),
style: Constants.buttonStyle),
const SizedBox(width:170),
ElevatedButton(
onPressed: () async {
final SharedPreferences prefs = await _prefs;
playLocalAsset(0);
if ((isFasting = true) && (widget.isFasting = true)) {
showError();
removeHours(fastDurs);
setState(() {
isFasting = false;
widget.isFasting = false;
});
//showAlerts();
} else {
setState(() {
isFasting = true;
widget.isFasting = true;
fastDuration = 18;
eighteen = 18;
sixteen = null;
twenty= null;
twentytwo = null;
twentyfour = null;
widget.fastDuration = 18;
endTime = startTime.add(Duration(hours: fastDuration!));
endTimeS = DateFormat('y/M/d, hh:mma').format(endTime);
_textLine = prefs
.setString('formattedDate', endTimeS)
.then((value) =>
(prefs
.getString('formattedDate') ??
Languages.of(context)!.setYourFastTime + '\n' + startTimeS));
textDate =
prefs.setString('eatTime', Languages.of(context)!.youWillEatAt)
.then((value) => (prefs.getString('eatTime') ?? ''));
showMessage(Languages.of(context)!.yourFastTimeIsSet);
updateHours(18);
});
}
showNotificationOneTime(context,
startTime.add(const Duration(hours: 14)).hour,
startTime.add(const Duration(minutes: 0)).minute);
showNotif(context,
endTime.hour, endTime.minute);},
child: Text('18:6', style: Constants.textTitleStyle),
style: Constants.buttonStyle
),
i declare my isFasting bool as nullable, then in init I check for the time, and if it is before the endTime then bool isFasting = true. As such:
#override
void initState() {
super.initState();
String startTimeS = DateFormat('y/M/d, hh:mma').format(startTime);
String endTimeS = DateFormat('y/M/d, hh:mma').format(endTime);
_textLine = _prefs.then((SharedPreferences prefs) {
String? fastEndTime = prefs.getString('formattedDate');
if ((fastEndTime != null) && (endTime
.isAfter(DateFormat('y/M/d, hh:mma').parse(fastEndTime)))) {
setState(() {
isFasting = false;
widget.isFasting = false;
});
return Languages.of(context)!.yourFastTimeFinished +"\n"+ endTimeS;
}
if (isFasting = false) {
return Languages.of(context)!.setYourFastTime +"\n"+ startTimeS;
}
if ((fastEndTime != null) && (endTime
.isBefore(DateFormat('y/M/d, hh:mma').parse(fastEndTime)))){
setState(() {
isFasting = true;
widget.isFasting = true;
});
}
return fastEndTime ??
Languages.of(context)!.setYourFastTime + "\n" + startTimeS;
});
textDate = _prefs.then((SharedPreferences prefs) {
String? stillFastingTime = prefs.getString('eatTime');
String? fastEndTime = prefs.getString('formattedDate');
if ((fastEndTime != null) && (endTime
.isBefore(DateFormat('y/M/d, hh:mma').parse(fastEndTime)))) {
setState(() {
isFasting = true;
widget.isFasting = true;
});
return Languages.of(context)!.youWillEatAt;
}
return stillFastingTime ?? '';
});
}
so, if isFasting is true then fast is cancelled and isFasting set to false. then clicking on a diff button should set state as shown in else condition. However, my isFasting is always true. it does not turn off... And it does not remove the previous hours, and it does not change the string of the text according to state. How do I make that bool value work properly? Thank you for your help!
use == instead of = when checking for equality:
if (isFasting = false) to if (isFasting == false)
and
if((isFasting = true) && (widget.isFasting = true)) to if(isFasting == true && widget.isFasting == true) also the braces here can be removed.
!= is correct here

flutter google_speach response stream not working

final serviceAccount = ServiceAccount.fromString(r'''{
Json private keys
}''');
final speechToText = SpeechToText.viaServiceAccount(serviceAccount);
final config = RecognitionConfig(
encoding: AudioEncoding.LINEAR16,
model: RecognitionModel.basic,
enableAutomaticPunctuation: true,
sampleRateHertz: 16000,
languageCode: 'en-US');
final streamingConfig =
StreamingRecognitionConfig(config: config, interimResults: true);
Stream<List<int>> stream =
(await MicStream.microphone(sampleRate: 16000)) as Stream<List<int>>;
final responseStream =
speechToText.streamingRecognize(streamingConfig, stream);
if (_isListining) {
setState(() {
_isListining = false;
});
} else {
setState(() {
_isListining = true;
print('hello');
try {
responseStream.listen((data) {
print(data.results.length);
setState(() {
_sendController.text = data.results
.map((e) => e.alternatives.first.transcript)
.join('/n');
});
print(content);
}, onDone: () {
setState(() {
setState(() {
_isListining = false;
});
});
}, onError: (e) {
print('errorr : ' + e);
setState(() {
_isListining = false;
});
});
print('streaming');
} catch (e) {
print('not streaming');
print(e);
}
});
}
linke to packages used
https://pub.dev/packages/google_speech
https://pub.dev/packages/mic_stream
so the problem is that microphone streaming is working fine but responseStream from google apis not printing or doing anything
after reading the docs
found this
https://cloud.google.com/speech-to-text/docs/troubleshooting#returns_an_empty_response
and i dont know if it is the problem or not

How do i create a rounded search bar in flutter that also shows the recent searches from the search bar?

I have been wanting to find a solution to create a rounded search bar in flutter which also shows the list of recent searches underneath it. How is it possible to create the previous widget?
Using the package below, you can save the information you want to the device memory and then withdraw it from there (username, password, search history, etc.). The sample code is in the document.
https://pub.dev/packages/shared_preferences
like this:
void handleRememberMe(bool? value) {
_isChecked = value!;
SharedPreferences.getInstance().then(
(prefs) {
prefs.setBool("remember_me", value);
prefs.setString('userName', userNameController.text);
prefs.setString('password', passwordController.text);
},
);
setState(() {
_isChecked = value;
});
}
void loadUserEmailPassword() async {
try {
SharedPreferences _prefs = await SharedPreferences.getInstance();
var _email = _prefs.getString("userName") ?? "";
var password = _prefs.getString("password") ?? "";
var _remeberMe = _prefs.getBool("remember_me") ?? false;
if (_remeberMe) {
setState(() {
_isChecked = true;
});
userNameController.text = _email;
passwordController.text = password;
} else {
userNameController.text = "";
passwordController.text = "";
setState(() {
_isChecked = false;
});
}
} catch (e) {
debugPrint(e.toString());
}
}

Wait for callback to complete in Dart / Flutter

Currently writing a flutter app using the flutter_tts library.
I have a list of sentences to read out, but currently having trouble waiting for the setCompletionHandler() to complete.
How can I wait for the setCompletionHandler() callback to complete before moving on to the next string? Currently, the TTS.speak() function finishes immediately with the while loop incrementing right away so it only reads out the last sentence in the list.
// code shortened for brevity
FlutterTts TTS;
TtsState ttsState = TtsState.stopped;
get isPlaying => ttsState == TtsState.playing;
get isStopped => ttsState == TtsState.stopped;
List<String> sentences = ['Hello, World', 'How are you?', 'The quick brown fox jumps over the lazy dog'];
#override
void initState() {
super.initState();
TTS = FlutterTts();
}
void readOutSentences(sentences) async {
int i = 0;
bool readCompleted = false;
while (i < sentences.length) {
readCompleted = await runSpeak(sentences[i].toString());
if (readCompleted)
i++;
}
}
Future<bool> runSpeak(String currentSentence) async {
TTS.setStartHandler(() {
setState(() {
ttsState = TtsState.playing;
});
});
TTS.setCompletionHandler(() {
setState(() {
ttsState = TtsState.stopped;
});
});
await TTS.speak(currentSentence);
return true;
}
readOutSentences(sentences);
Forgive about the setCompletionHandler)
You can use such async functions:
Future<void> _speak(String _text) async {
if (_text != null && _text.isNotEmpty) {
await flutterTts.awaitSpeakCompletion(true);
await flutterTts.speak(_text);
}
}
readAllSentencesList(List<String> allSentences) async {
for (int i=0; i<allSentences.length; i++){
await _speak(allSentences[i]);
}
}
Don't forget to use last flutter_tts library!
Set setCompletionHandler like following to speak all sentences of the list one by one.
List<String> sentences = ['Hello, World', 'How are you?', 'The quick brown fox jumps over the lazy dog']
int i = 0;
FlutterTts flutterTts = FlutterTts();
await flutterTts.speak(sentences[i]);
flutterTts.setCompletionHandler(() async {
if (i < sentences.length - 1) {
i++;
await flutterTts.speak(sentences[i]);
}
});
To wait for the callback use the await keyword:
await TTS.setCompletionHandler(() {
setState(() {
ttsState = TtsState.stopped;
});
});