Barcode crash without errors - flutter

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 = '');
}
}

Related

How to pass data from a Barcode scanner to a Textfield (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

Unhandled Exception: Null check operator used on a null value Uint8List

Unhandled Exception: Null check operator used on a null value
Friends, I have indicated the place where the error is below and I tried a few things, but I still could not get rid of this error. Does anyone know the solution?
When I remove ! from _image!, I still get an error.
Uint8List? _image;
signUpUser() async {
// set loading to true
setState(() {
_isLoading = true;
});
String res = await AuthMethods().signUpUser(
email: _emailController.text,
password: _passwordController.text,
username: _usernameController.text,
bio: _bioController.text,
gender: _genderController.text,
file: _image! //--> error);
if (res == "success") {
setState(() {
_isLoading = false;
});
Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage()));
} else {
setState(() {
_isLoading = false;
});
// show the error
showSnackBar(context, res);
}
}
selectImage() async {
Uint8List im = await pickImage(ImageSource.gallery);
setState(() {
_image = im;
});
}
The _image is null. I don't see where you call the selectImage() function, and other than that function _image is never defined. Even if selectImage() was called, when the picker appears the user may not actually pick an image and cancel it or another error can happen. The AuthMethods().signUpUser() method seems to not allow the file parameter to be null, that's why when you remove the ! it doesn't work.

How to use function output as a conditional of IF ELSE or Ternary operator

So for some background, I implemented a function that reads from Firebase's real-time database and returns a child node. I have built a button that is meant to check if that function returns the object or null if the function returns an object I want the snack bar to display a message.
ElevatedButton(
onPressed: () {
if (validateUsername() != null) {
print("conditional: test");
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text(
"Username has been taken please try a different one"),
duration: Duration(seconds: 5)));
} else {
return null;
}
},
I had some success with the function by turning it into an async function
validateUsername() async {
final database = FirebaseDatabase.instance.ref().child("/takenUsernames");
await database
.child(_usernameController.text.trim())
.once()
.then((DatabaseEvent event) {
final snapShot = event.snapshot;
final value = snapShot.value;
print("function result: $value");
return value;
});
}
When I turn it to an async function the snack bar displays the message but unfortunately even when the conditional is equal to a null, it for some reason continues to display the message and prints the "test"output. But if I were to try taking away the async the snack bar doesn't print and the "test" in the conditional doesn't print.non-async output
Any help would be appreciated and thanks for your time.
Try this approach, using the await in a variable will wait for the value then the if will evaluate what the result.
ElevatedButton(
onPressed: () async {
String validation = await validateUsername(); // I used type String but you should use the type that will be return.
if (validation != null) {
print("conditional: test");
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text(
"Username has been taken please try a different one"),
duration: Duration(seconds: 5)));
} else {
return;
}
},
)
add try/catch
validateUsername() async {
try {
final database = FirebaseDatabase.instance.ref().child("/takenUsernames");
await database
.child(_usernameController.text.trim())
.once()
.then((DatabaseEvent event) {
final snapShot = event.snapshot;
final value = snapShot.value;
print("function result: $value");
return value;
});
} catch(e) {
print("err $e");
return null;
}
}
Thanks to some help from #WilsonToribio, I was able to use the information he gave and also implement a few changes to the validateUsername() function
as seen here
validateUsername() async {
try {
final database = FirebaseDatabase.instance.ref().child("/usernames");
final response = await database
.child(_usernameController.text.trim())
.once()
.then((event) {
final dataSnapshot = event.snapshot;
if (dataSnapshot.value != null) {
return dataSnapshot.value;
}
});
return response;
} catch (e) {
print("err $e");
return null;
}
}

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

How to use barcode result to open webview in flutter

I am using BarcodeScanner package. I get the result after scan the QR code. My question is how to use that result then open the website. Here is my code:
Future scan() async{
Completer<WebViewController> _controller = Completer<WebViewController>();
try {
String barcode = await BarcodeScanner.scan();
setState(() {
this.barcode = barcode;
print(this.barcode);
WebView(
initialUrl: this.barcode,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
),
});
} on PlatformException catch (e) {
if (e.code == BarcodeScanner.CameraAccessDenied) {
setState(() {
this.barcode = 'The user did not grant the camera permission!';
});
} else {
setState(() => this.barcode = 'Unknown error: $e');
}
} on FormatException{
setState(() => this.barcode = 'null (User returned using the "back"-button before scanning anything. Result)');
} catch (e) {
setState(() => this.barcode = 'Unknown error: $e');
}
}
}
If you use Webview here, after you receive QR code from scanner you need you navigate to new screen. Like this
Navigator.push(
context,
MaterialPageRoute(builder: (context) => WebView(initUrl: data[index].homeLink))
);
Otherwise, you can use url_launcher plugin
https://pub.dev/packages/url_launcher
controller.pauseCamera();
if (await canLaunch(scanData.code)) {
await launch(scanData.code);
}
controller.resumeCamera();
For more details, see here