How to pass data from a Barcode scanner to a Textfield (Flutter) - flutter

I am using the 'flutter_barcode_scanner' package and I want to pass some data from the barcode scanner to a TextField in the app that I am working on.
I have a TextEditingController like this:
var searchController = TextEditingController();
And the code I use for the barcode scanner is this:
Future<void> scanBarcodeNormal() async {
String barcodeScanRes;
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode('#ff6666', 'Cancel', true, ScanMode.BARCODE);
print(barcodeScanRes);
} on PlatformException {
barcodeScanRes = 'Cihazınız barkod okumayı desteklemiyor.';
}
if (!mounted) return;
setState(() {
_scanBarcode = barcodeScanRes;
});
}
I know that I need to change some things in the last part,
if (!mounted) return;
setState(() {
_scanBarcode = barcodeScanRes;
});
I want to replace the setState(() {}) with a code that achieves what I want (Passing the data from the barcode to the TextField.)
I am trying to replace the setState(() {}) of the barcode scanner with a code that passes the data to TextField.

Try replacing this statement
setState(() {
_scanBarcode = barcodeScanRes;
});
With this
searchController.text = barcodeScanRes;
Gist: https://gist.github.com/SteplerPaulo/cee0e6f03fb8c1b7a5014074f665594b

Related

Flutter how do you return value or error from stream

I want to use this method, but instead of returning Future<void>, I want to return a value from it. This value is either a final list of bytes or an error (if error happens anytime).
I don't know how to that, since you can't return a value from onDone or onError. If I use await for instead of listen, the errors behave strangely. How to do that?
Future<void> _downloadImage() async {
_response = await http.Client()
.send(http.Request('GET', Uri.parse('https://upload.wikimedia.org/wikipedia/commons/f/ff/Pizigani_1367_Chart_10MB.jpg')));
_total = _response.contentLength ?? 0;
_response.stream.listen((value) {
setState(() {
_bytes.addAll(value);
_received += value.length;
});
}).onDone(() async {
final file = File('${(await getApplicationDocumentsDirectory()).path}/image.png');
await file.writeAsBytes(_bytes);
setState(() {
_image = file;
});
});
}

setState() called after dispose() error after calling async function

I have this button that uploads to Firestore a picture that the user selects and stores the picture url into a varialble to be used to update the user's information.
SELECTION BUTTON calls selectFile().
// SELECTING FILE FOR UPLOAD
Future selectFile() async {
final result = await FilePicker.platform
.pickFiles(allowMultiple: false, type: FileType.image, withData: true);
if (result == null) return;
setState(() {
pickedFile = result.files.first;
texto = Text(pickedFile!.name);
});
}
This successfully changes the state of pickedFiles and Texto variable.
Then I have this other button later in the code that calls uploadFile() and then exits the page with navigator.pop(context).
// UPLOADING FILE AND RETRIEVING DOWNLOAD LINK
Future uploadFile() async {
var fileBytes = pickedFile?.bytes;
var fileName = pickedFile?.name;
var ref = FirebaseStorage.instance.ref().child('UserImages/$fileName');
if (fileBytes == null) {
return '';
}
TaskSnapshot uploadedFile = await ref.putData(fileBytes);
url = await ref.getDownloadURL();
log(url);
if (uploadedFile.state == TaskState.success) {
setState(() { <<<<<<<<--------- setState() called after dispose() ERROR HERE
_petImage = url;
});
}
}
The function does upload the picture to FireStore and even produces a link (tested by using log(url)) but when it reaches the set state it fails.
I have no idea why this is not updating the state of the _petImage variable which stored outside of the main build(context) together with the other variables suck as pickedFile and texto. the setState work fine in other functions but in this function is not working .
what could I be doing wrong here?
It is safe to check if the state is mounted on async and then perform setState.
_() async {
if (mounted) {
setState(() {});
}
}

An alert dialog is not displayed at the widget load, why?

In my application I am reading a qr code with the flutter_barcode_scanner package, and when reading a valid code it is supposed to show me an alert dialog saying that it is correct, otherwise, well, no.
To implement this package, an example tells us that based on an action (such as pressing a button) start the scanning method, and save what is read in a variable. Thus:
Future<void> scanQr() async {
try {
final qrCode = await FlutterBarcodeScanner.scanBarcode(
'#ffffff', 'Cancel', true, ScanMode.QR);
if (!mounted) {
return;
}
setState(() {
this.qrCode = qrCode.isEmpty
? 'EMPTY'
: qrCode == '-1'
? 'INVALID'
: qrCode;
});
} on PlatformException {
qrCode = 'fail';
}
}
We can see what the set state occupies in order to update the value. This in a variable that, as you can see, is called qrCode. Which in the example puts it in a text widget and it works fine. when reading something, it is updated.
So, what I want to do is a simple validation, and based on said validation, show an alertdialog saying if what was read in the qr is right or wrong.
I have my validation in the same setstate, I ask if a certain part of the read string looks like what I want. Likewise, I have an int variable, which when updated in the set state, draws an alertdialog.
Future<void> scanQr() async {
try {
final qrCode = await FlutterBarcodeScanner.scanBarcode(
'#ffffff', 'Cancel', true, ScanMode.QR);
if (!mounted) {
return;
}
setState(() {
this.qrCode = qrCode.isEmpty
? 'EMPTY'
: qrCode == '-1'
? 'INVALID'
: qrCode;
});
if (qrCode.substring(0, 2) == 'somepattern') {
setState(() {
value = 1;
});
} else {
setState(() {
value = 2;
});
}
//saveContact(qrCode);
} on PlatformException {
qrCode = 'fail';
}
}
In the build method I have:
String qrCode = '';
int value = 0;
#override
Widget build(BuildContext context) {
//Future(() async {
(value == 1)
? alerta('Yeah', "This code are right!")
: (value == 2)
? alerta(
'Oh no!', 'An invalid qr code')
: null;
//});
return Scaffold(...
As you can see, I even try it with a future to give it time to draw, but it doesn't show any alertDialog. The text widget with the each is displayed. Even, i print the value, and its right, prints 2 and 1 respectively; but the alert dialog is never showed
Why doesn't it draw my alert dialog? What am I doing wrong?
Instead of writing the alert dialog logic inside build method, you should have it in scanQR method
Future<void> scanQr() async {
try {
final qrCode = await FlutterBarcodeScanner.scanBarcode(
'#ffffff', 'Cancel', true, ScanMode.QR);
if (!mounted) {
return;
}
setState(() {
this.qrCode = qrCode.isEmpty
? 'EMPTY'
: qrCode == '-1'
? 'INVALID'
: qrCode;
});
if (qrCode.substring(0, 2) == 'somepattern') {
setState(() {
value = 1;
alerta('Yeah', "This code are right!");
});
} else {
setState(() {
value = 2;
alerta(
'Oh no!', 'An invalid qr code');
});
}
//saveContact(qrCode);
} on PlatformException {
qrCode = 'fail';
}
}
Try this and let me know.

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());
}
}

Barcode crash without errors

I am making an app using the qrCode scanner and when i open the app on my iphone and touch the button for the qrCode scanning it shuts down automatically , not opening even the camera.I used barcode_scan in pubspec.yaml and the code is:
String qrResult = "Not yet Scanned";
onPressed: () async {
String scaning = await BarcodeScanner.scan();
setState(() {
qrResult = scaning;
});
},
The app is made in flutter
Please You can use this package flutter_barcode_scanner 1.0.1 to make your Work Simple.Cheers!!
scan() async {
try {
dynamic bar = await BarcodeScanner.scan();
if(bar != null && bar.isNotEmpty){
print(" scanning qrcode ------------------------ $barcode");
setState(() {
barcode = bar;
});
}} on PlatformException catch (e) {
setState(() => this.barcode = '');
} on FormatException{
setState(() => this.barcode = '');
} catch (e) {
setState(() => this.barcode = '');
}
}