Flutter - Close barcode scanner after scan in flutter - android

I am using this package package for scanning barcode. It works fine but after successfully scan I want to close the camera. I searched for the solution but no solution worked in my case. Here is my code.
try {
FlutterBarcodeScanner.getBarcodeStreamReceiver(
'#ff6666', 'Cancel', true, ScanMode.BARCODE)!
.listen((data) {
print(data);
});
} on PlatformException {
// barcodeScanRes = 'Failed to get platform version.';
}
}

you can close scan page by adding this line to your code
if (barcodeScanRes != null){
print(barcodeScanRes);
// this will send your scan result to previous page
// or you can navigate to other page after scan success
Navigator.pop(context, barcodeScanRes);
}
String barcodeScanRes; // put this variable in statefull widget
Future<void> scanQR() async {
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.QR);
// add this line to close scanner or naivigate to other page
if (barcodeScanRes != null){
print(barcodeScanRes);
Navigator.pop(context, barcodeScanRes);
}
} on PlatformException {
barcodeScanRes = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_scanBarcode = barcodeScanRes;
});
}
or if you want to pause the camera after scan, you can use this package https://pub.dev/packages/qr_code_scanner

Related

When using Firebase login, it is always automatically logged in [duplicate]

Main Dart:
Widget build(BuildContext context) {
return StreamProvider<MyUser?>.value(
value: AuthService().user,
initialData: null,
child: MaterialApp( //code for material dart
Wrapper Widget:
Widget build(BuildContext context) {
final user = Provider.of<MyUser?>(context);
print(user);
if (user == null) {
print('no one logged in');
} else {
print(user.uid);
}
return user == null ? LoginPage() : NavigationBar();
}
So I'm trying to load the login page whenever user is null, but I only logged in the first time and now it stays logged in even after deleting that account from firebase console.
Output after hot restart:
Restarted application in 935ms.
flutter: null
flutter: no one logged in
flutter: Instance of 'MyUser'
flutter: ETBVvt2A0JggH8KSrgdLh3DP8cG3
I don't get why the first time it returns
'no one logged in' but it runs a second time too and returns the uid of the user that is logged in.
The logout button doesn't work either. It does't return an error or anything, it just doesn't produce any output.
Here is the signOut button method:
//method
final FirebaseAuth _auth = FirebaseAuth.instance;
Future signOut() async {
try {
return await _auth.signOut();
} catch (error) {
print(error.toString());
return null;
}
Signout button:
onPressed: () async {
dynamic result = await _auth.signOut();
if (result == null) {
print('error signing out');
} else {
print('signed out');
Navigator.pushReplacementNamed(
context, LoginPage.routeName);
}
},
Firebase automatically persists the user credentials locally, and tries to restore those when the app is restarted.
To sign the user out, you have to explicitly sign the user out by calling await FirebaseAuth.instance.signOut().
Apparently the problem wasn't with firebase but with the custom button I had built. I didn't assign the onPressed properly and the logout button wasn't working because of that.
Please call this function in your oppressed area
Future<Null> _signOut() async { await GoogleSignIn().signOut(); print("logout Successfully"); }
Here GoogleSignIn(), is the function where you define your signin codes

Flutter: Get the variable after the running of a function

I'm having a problem getting a variable after the function runs.
I have to read a qr code and then put the qr code in a text field, but when i try to read it gets the default variable text, and only gets the right qr code when i try to read for the seccond time.
Here is the qr reader function:
Future<void> scanQR() async {
String barcodeScanRes;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.QR);
print(barcodeScanRes);
} on PlatformException {
barcodeScanRes = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_scanBarcode = barcodeScanRes;
});
}
Here the button to run the function and then put the qr on the controller:
onPressed: () {
scanQR();
setState(() {
_codprodController.text = _scanBarcode;
});
},
//on the first time i try it shows "unknown" that is the _scanBarCode default text instead of the qr i read
I guess the problem is the "_codprodController.text = _scanBarcode;" that its not runnig after (but together) the scanQR() but i dont know hot to fix.
Try below
onPressed: () async {
await scanQR();
setState(() {
_codprodController.text = _scanBarcode;
});
},

react-native-audio-recorder-player , audioRecorderPlayer.stopRecorder() crahs app

react-native-audio-recorder-player, library for use in my project to record audio.
When I start recording everything works fine, but close the application when I call the function to stop recording the audio "audioRecorderPlayer.stopRecorder ()".
It works perfectly on IOS (emulator and real device), and on Android emulator, but, it doesn't work on real android device.
What could be the cause of this error and how could it be resolved?
"react-native": "0.63.3",
"react-native-audio-recorder-player": "^2.6.0-rc3",
hooks for control
const [record, setRecord] = useState(false);
start record function
async function handleRecord() {
try {
const permissions = await getPermissions();
if (permissions) {
const path = Platform.select({
ios: `audio-${new Date().getTime()}.m4a`,
android: `sdcard/audio-${new Date().getTime()}.mp3`
});
const audioSet = {
AudioEncoderAndroid: AudioEncoderAndroidType.AAC,
AudioSourceAndroid: AudioSourceAndroidType.MIC,
AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,
AVNumberOfChannelsKeyIOS: 2,
AVFormatIDKeyIOS: AVEncodingOption.aac
};
const result = await audioRecorderPlayer.startRecorder(path, audioSet);
setRecord(true);
audioRecorderPlayer.addRecordBackListener(e => {
return;
});
}
} catch (err) {
}
}
stop record function
async function onStopRecord() {
try {
const result = await audioRecorderPlayer.stopRecorder();
audioRecorderPlayer.removeRecordBackListener();
setRecord(false);
setFiles([
...files,
{
uri: result,
type: "audio/mpeg",
name: `audio-${new Date().getTime()}.mp3`
}
]);
}catch(error){
Alert.alert(
"Erro",
error
);
}
}

Expo Permissions returns status of 'undetermined'

In my react native app, I ask for permission to access the camera roll as so:
getPermissionAsync = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status !== "granted") {
alert("Sorry, we need camera roll permissions to make this work!");
}
await this.setState({ permission: status === "granted" });
};
_pickMedia = async (index, type) => {
if (this.state.permission != true) {
await this.getPermissionAsync();
}
if (this.state.permission == true) {
// get image
} catch (E) {
console.log(E);
}
}
};
This works as expected during testing, but for my published version on Google Play, status is returned as undetermined whether or not the user gives permission. What does this mean?
Upgrading the react-native-community#react-native-permissions to 2.0.0 solves the issue.
Refer : https://github.com/react-native-community/react-native-permissions/issues/295

React Native AsyncStorage stops working once app is offline

I have a relatively simple app (my first) that needs to display information that is retrieved from a GraphQL query and then stored in AsyncStorage. Everything works fine until you turnoff data/Wifi connections and relaunch the app - it will not load the same local data it did when networking is on. This is the same on a physical or emulated Android device.
There are no data calls except when the user initially sets their details. The app is built with version 2.7.1 of Expo & AWS Amplify. I have wasted several days with this final issue and gotten the same behaviour with Expo SecureStore & Amplify Cache and am loath to go down the route of learning and including Redux on such a simple app...
//import from react native not react
import { AsyncStorage } from 'react-native'
//calling a function as app loads
componentDidMount() {
this._loadInitialState();
}
//retrieving String from AsyncStorage
_loadInitialState = async () => {
try {
const policyNum = await AsyncStorage.getItem('policyNum')
//...
} catch {
//...
}
//setting state
if (policyNum != null && policyNum != undefined) {
this.setState({ policyNum: policyNum })
//...
}
//the original setting of the item
setPolicyDetails = async () => {
if (this.state.policyNum != null) {
const policyNumber = this.state.policyNum
this.state.policyNumSet = true
try {
await AsyncStorage.setItem('policyNum', policyNumber)
} catch (err) {
//...
}
}
}
You are using badly the fact of change the state.
Where you do this:
this.state.policyNumSet = true
You should change the state with the setState() function like this:
this.setState({ policyNumSet: true })
This was a conflict with an external API
Are you storing a string? asyncstorage only can store strings . try using JSON.stringify and JSON.parse
_loadInitialState = async () => {
try {
var policyNum = await AsyncStorage.getItem('policyNum')
policyNum = JSON.parse(policyNum) // converting to original
//...
} catch {
//...
}
//setting state
if (policyNum != null && policyNum != undefined) {
this.setState({ policyNum: policyNum })
//...
}
//the original setting of the item
setPolicyDetails = async () => {
if (this.state.policyNum != null) {
const policyNumber = this.state.policyNum
this.setState({ policyNumSet: true })
try {
var policyNumberString = JSON.stringify(policyNumber)
await AsyncStorage.setItem('policyNum', policyNumberString) //converting to string
} catch (err) {
//...
}
}
}

Categories

Resources