barcode flutter scan doesn't get result mobile app - flutter

I try to read barcode using flutter mobile, I using this function
scanbarcode() async {
await FlutterBarcodeScanner.scanBarcode(
'#000000', 'Cancel', true, ScanMode.BARCODE)
.then((value) => setState(() => text = value));
}
it open camera and show scan line but it doesn't get the result it text, and when I press back or cancel it get me -1 in txt.
and that when I call
onPressed: () async {
await scanbarcode();
}
thanks

I know that on emultated phones bar and Qr code scanner do not work well so try to run your app on a real device. Otherwise I cannot help you more with your problem but I implemented a bar/QR code scanner few day ago with the qr_code_scanner: ^1.0.0 package and it worked for me.
Hier is the link of the package: https://pub.dev/packages/qr_code_scanner
and here the code exemple:
#override
Widget build(BuildContext context) {
final qrKey = GlobalKey(debugLabel: 'QR');
QRViewController? controller;
void onQRViewCreated(QRViewController controllerAt) {
controller = controllerAt;
controllerAt.pauseCamera();
controller!.resumeCamera();
controller!.scannedDataStream.listen((barcode) {
// Hier you get the barcode or qr code if it's scanned
});
}
Widget _getBarQrScannerWidget() {
return QRView(
key: qrKey,
onQRViewCreated: onQRViewCreated,
overlay: QrScannerOverlayShape(
cutOutSize: MediaQuery.of(context).size.width * 0.75,
borderWidth: 10,
borderLength: 15,
borderRadius: 8,
),
);
}
return getBarQrScannerWidget()
}

Related

Flutter text to speech (flutter_tts) does not work

I am trying to build this simple text to speech feature using flutter_tts package but it doesn't speak no matter what I tried (official example, tutorials, etc.)
I checked my Audio Output, it's set correctly. I have other MP3 sounds, they play just fine.
I tried ^3.5.0 and ^3.5.3 versions, neither worked.
Here is my code:
class ColorsScreen extends StatefulWidget {
const ColorsScreen({super.key, required this.title});
final String title;
#override
State<ColorsScreen> createState() => _ColorsScreenState();
}
class _ColorsScreenState extends State<ColorsScreen> {
late FlutterTts flutterTts;
bool isPlaying = false;
String _currentColor = "black";
String get currentColorName =>_currentColor;
#override
void initState() {
super.initState();
initTts();
flutterTts.setStartHandler(() {
setState(() {
isPlaying = true;
});
});
flutterTts.setCompletionHandler(() {
setState(() {
isPlaying = false;
});
});
}
initTts() async {
flutterTts = FlutterTts();
}
Future _readColorName() async {
await flutterTts.setVolume(1);
await flutterTts.setSpeechRate(1);
await flutterTts.setPitch(1);
var result = await flutterTts.speak(currentColorName);
if (result == 1) {
setState(() {
isPlaying = true;
});
}
}
#override
void dispose() {
super.dispose();
flutterTts.stop();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: TopBar(widget.title),
body: IconButton(
padding: const EdgeInsets.all(0),
icon: const Icon(
Icons.play_circle_fill_rounded,
color: Colors.red,
size: 50,
semanticLabel: 'Play color name',
),
onPressed: _readColorName,
),
);
}
}
Try in different real android devices such as: Android 11 or Android 12
I had recently upgraded my simulator to iOS 16.0 and now realizing that's the problem. Switched to a iOS 15.5 simulator and it worked fine. When on iOS 16.0, XCode console was showing this error: "unable to list voice folder" Leaving it here in case someone else faces a similar problem. I will continue building in iOS 15.5 version for now and keep checking if the libraries get any updates.

How to make showDIalog wait for a function to finish first before building widget

So I'm trying to create a qr scanner feature, I manage to do all the function and functionality for the code, but when my code try to fetch the data the widget build run first resulting some data is null. How can I make the showDialog widget to wait for my function to be done first before moving on in building the data ?
Here's my code:
void getQRData() async {
// Get User Data from ID
print('qrcode: $qrcode');
// Take the UserData[Number] to get user short data
data = await UserDatabase.getUserShortData(
userId: qrcode,
phoneNumber: null,
);
print('data is : $data');
await Future.forEach(
Provider.of<ContactDataProvider>(context, listen: false)
.getContactConnection
.keys, (key) async {
connectedContactData =
Provider.of<ContactDataProvider>(context, listen: false)
.getContactConnection[key];
print(connectedContactData);
if (connectedContactData['status'] == 'connected' ||
connectedContactData['status'] == 'sent_req') {
filteredId.add(connectedContactData['contact_uid']);
print('filteredId: ${filteredId}');
}
});
}
Container(
width: 250,
height: 250,
child: ScanView(
controller: scanController,
scanAreaScale: 0.8,
scanLineColor: Colors.red,
onCapture: (photoData) {
qrcode = photoData;
print('qrcode: $qrcode');
getQRData();
print(data);
//ShowDialog Widget Code
},
),
),
On the code above, my showDialog widget code run first before the getQRData() function is done. Resulting the widget is always error because the data is still null. Like what I just print
Firstly, convert getQRData method from void to future.
Future<void> getQRData() async {...}
Now on onCapture
onCapture: (photoData) async {
qrcode = photoData;
await getQRData();
await showDialog(...);
},
More about dart async-await

Flutter barcode scanner on mobile web app

I have a barcode scanner working fine on Android, but I am struggling to find plugins that support a web app.
This is the closest one I've found that seems to be getting somewhere:
https://pub.dev/packages/ai_barcode
But I can't really get anything to happen.
Here is the code I'm using currently:
import 'package:flutter/material.dart';
import 'package:ai_barcode/ai_barcode.dart';
class WebBarcodeScannerPage extends StatefulWidget {
// void resultCallback (String result) {
// debugtext
// }
#override
_WebBarcodeScannerPageState createState() => _WebBarcodeScannerPageState();
}
class _WebBarcodeScannerPageState extends State<WebBarcodeScannerPage> {
ScannerController _scannerController;
String _debugText = 'debug';
#override
void initState () {
super.initState();
_scannerController = ScannerController(scannerResult: (r) => resultCallback(r));
// _scannerController = ScannerController(scannerResult: (result) {
// resultCallback(result);
// }, scannerViewCreated: () {
// final TargetPlatform platform = Theme.of(context).platform;
// if (TargetPlatform.iOS == platform) {
// Future.delayed(const Duration(seconds: 2), () {
// _scannerController
// ..startCamera()
// ..startCameraPreview();
// });
// } else {
// _scannerController
// ..startCamera()
// ..startCameraPreview();
// }
// });
}
resultCallback (String r) {
print(r);
setState(() {
_debugText = r;
});
}
_body () {
return Column(
children: [
Text(_debugText),
TextButton(
child: Text('Start camera'),
onPressed: () {
_scannerController.startCamera();
},
),
TextButton(
child: Text('Start preview'),
onPressed: () {
_scannerController.startCameraPreview();
},
),
TextButton(
child: Text('Stop camera'),
onPressed: () {
_scannerController.stopCamera();
},
),
TextButton(
child: Text('Stop preview'),
onPressed: () {
_scannerController.stopCameraPreview();
},
),
PlatformAiBarcodeScannerWidget(platformScannerController: _scannerController),
],
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: _body(),
);
}
}
The camera preview shows up in a window, but I can't scan any barcodes or QR codes. The debug text never changes.
Again, my goal is to be able to read barcodes into a string on a mobile web app.
You can use our product Cognex Mobile Barcode SDK
Download page for all supported platforms - https://cmbdn.cognex.com/download#Platforms
Knowledge Base for more information about the integration - https://cmbdn.cognex.com/v2.6.x/knowledge/flutter/license-keys
https://pub.dev/packages/cmbsdk_flutter
Regards,
You should add jsQR.js to web folder.
You can find that HERE
you can use the source example from ai_barcode.
QRCodeDartScanView(
typeCamera: TypeCamer.front,
scanInvertedQRCode: true,
resolutionPreset: QRCodeDartScanResolutionPreset.ultraHigh,
formats: const [
BarcodeFormat.QR_CODE,
],
onCapture: (Result result) {
printInfo(info: result.text);
},
);
Just put this piece of code inside a build method. The camera opens and read qr codes.
simple_barcode_scanner (which leverages html5-qrcode for web apps) worked best for my PWA, in fact it was the only package of several I tried that met my requirements of being able to read both EAN-13 and GS1 data matrix from a web app -- and it worked immediately the first time, and it does not require editing index.html. (I couldn't use ai_barcode due to a hard-to-resolve dependency conflict between ai_barcode and barcode, and barcode is a must-have for my web app -- but even without the dependency issue I struggled to make ai_barcode work reliably).
If you decide to use simple_barcode_scanner note that it does not work on desktop browsers, only mobile browsers, so you'll need a check like this:
import 'package:flutter/foundation.dart';
import 'package:simple_barcode_scanner/simple_barcode_scanner.dart';
...
final isWebMobile = kIsWeb &&
(defaultTargetPlatform == TargetPlatform.iOS ||
defaultTargetPlatform == TargetPlatform.android);
if (isWebMobile) {
String scanResult = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SimpleBarcodeScannerPage()),
);
print('scan result = $scanResult');
} else {
print('Scanning is only supported for mobile web browsers.');
}

Perform in app force update using current and required build numbers

I want to force update my app.
Here's what I have done so far.
Obtained the current build version of my app using package_info_plus
Obtained the enforced build version which I have stored in the firebase remote config. So I used this package: firebase_remote_config
I then compared the two build numbers to see if the update is needed. What should I do after that?
Here's my code:
void initState(){
super.initState();
checkForUpdate();
_initPackageInfo();
_enforcedVersion();
if(int.parse(_packageInfo.buildNumber) > int.parse(enforcedBuildNumber))
{
//How to force update?
}
}
Future<void> _initPackageInfo() async {
final info = await PackageInfo.fromPlatform();
setState(() {
_packageInfo = info;
});
}
Future<void> _enforcedVersion() async {
final RemoteConfig remoteConfig = RemoteConfig.instance;
await remoteConfig.setConfigSettings(RemoteConfigSettings(
fetchTimeout: const Duration(seconds: 10),
minimumFetchInterval: Duration.zero,
));
await remoteConfig.fetchAndActivate();
setState(() {
enforcedBuildNumber = remoteConfig.getString('enforced_build_number');
});
}
You could display a non dismissable dialog which would ask the user to update the application with a redirection button to the device appstore.
By using a package such as url_launcher you can easily do that:
Code Sample
import 'dart:io' show Platform;
import 'package:url_launcher/url_launcher.dart';
// You can show a dialog like this
showDialog(
context: context,
barrierDismissible: false,
builder: (_) => AlertDialog(
title: Text('Please update your app'),
actions: [
TextButton(
onPressed: launchAppStore,
child: Text('Open App Store'),
),
],
),
);
// Method to open the appstore
void launchAppStore() {
/// Depending on where you are putting this method you might need
/// to pass a reference from your _packageInfo.
final appPackageName = _packageInfo.packageName;
if (Platform.isAndroid) {
launch("https://play.google.com/store/apps/details?id=$appPackageName");
} else if (Platform.isIOS) {
launch("market://details?id=$appPackageName");
}
}

Download, save as, and change background image of the phone with Flutter

I need help regarding the images in my app. I would like to add 3 buttons for:
Download
Save as
Change phone wallpaper
I'm not using urls. I already have my images in an assets repository.
Do you have any idea how I can do that? Thank you.
You can copy paste run full code below
You can use package https://pub.dev/packages/wallpaper_manager
You can directly set wallpaper with image in assets
Example code's assets image path is "assets/tmp1.jpg"
code snippet
result = await WallpaperManager.setWallpaperFromAsset(
assetPath, WallpaperManager.HOME_SCREEN);
working demo
full code
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:wallpaper_manager/wallpaper_manager.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
String _wallpaperFile = 'Unknown';
String _wallpaperAsset = 'Unknown';
#override
void initState() {
super.initState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await WallpaperManager.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> setWallpaperFromFile() async {
setState(() {
_wallpaperFile = "Loading";
});
String result;
var file = await DefaultCacheManager().getSingleFile(
'https://images.unsplash.com/photo-1542435503-956c469947f6');
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await WallpaperManager.setWallpaperFromFile(
file.path, WallpaperManager.HOME_SCREEN);
} on PlatformException {
result = 'Failed to get wallpaper.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_wallpaperFile = result;
});
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> setWallpaperFromAsset() async {
setState(() {
_wallpaperAsset = "Loading";
});
String result;
String assetPath = "assets/tmp1.jpg";
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await WallpaperManager.setWallpaperFromAsset(
assetPath, WallpaperManager.HOME_SCREEN);
} on PlatformException {
result = 'Failed to get wallpaper.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_wallpaperAsset = result;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: <Widget>[
RaisedButton(
child: Text("Platform Version"),
onPressed: initPlatformState,
),
Center(
child: Text('Running on: $_platformVersion\n'),
),
RaisedButton(
child: Text("Set wallpaper from file"),
onPressed: setWallpaperFromFile,
),
Center(
child: Text('Wallpaper status: $_wallpaperFile\n'),
),
RaisedButton(
child: Text("Set wallpaper from asset"),
onPressed: setWallpaperFromAsset,
),
Center(
child: Text('Wallpaper status: $_wallpaperAsset\n'),
),
],
)),
);
}
}