How can you setup a flutter rawkeyboardlistener to read {} (curly brackets) instead of square brackets? - flutter

I have a flutter solution that interprets a QR code via a scanning device. I use the RawKeyboardListener to read the scanned QR code that then parses it into a variable.
The QR value is an object {something: somethingelse}, but when read by the RawKeyboardListener, it reads the {} as [] and as a result, the object is then invalid.
String runtime = event.runtimeType.toString();
if (event.data.logicalKey != LogicalKeyboardKey.enter) {
setState(() {
scannedItem += runtime == 'RawKeyUpEvent' ? event.data.keyLabel : '';
});
} else if (scannedItem != '') {
setState(() {
var data = json.decode(scannedItem);
});
}

I played around with the solution and ended up fixing it, though I do feel there is a better way of resolving this
if (event.data.isShiftPressed) {
switch (event.data.logicalKey.debugName) {
case 'Bracket Left':
keyLabel = '{';
break;
case 'Bracket Right':
keyLabel = '}';
break;
case 'Quote':
keyLabel = '"';
break;
case 'Semicolon':
keyLabel = ':';
break;
default:
keyLabel = keyLabel.toUpperCase();
break;
}
}

Related

Geofire query at location

I'm building an app which uses location. The people who are closer to 10 meters should be showed.
I use Geofire but the problem I'm facing is the value I pass to it's radius for it to get me people doesn't work at all. I pass 10 meters but when I calculate the distance using distance between, of the list of people it gave me I get 346 meters instead. Is it a problem from their end or mine? That is my code.
Geofire.queryAtLocation(position.latitude, position.longitude, chat)!.listen((map) {
print("This is the map: $map");
if (map != null) {
var callBack = map['callBack'];
double value = Geolocator.distanceBetween(position.latitude, position.longitude,
map['latitude'], map['longitude']);
print("Distance: $value meters");
switch (callBack) {
case Geofire.onKeyEntered:
NearByUsers nearbyUsers = NearByUsers();
nearbyUsers.key = map['key'];
nearbyUsers.latitude = map['latitude'];
nearbyUsers.longitude = map['longitude'];
if(value < chat) {
GeofireAssistant.nearbyAvailableUsers.add(nearbyUsers);
if (nearbyAvailableUserKeysLoaded == true) {
RequestAssistant.updateUsers();
}
}
break;
case Geofire.onKeyExited:
GeofireAssistant.removeDriveFromList(map['key']);
RequestAssistant.updateUsers();
break;
case Geofire.onKeyMoved:
NearByUsers nearbyUsers = NearByUsers();
nearbyUsers.key = map['keys'];
nearbyUsers.latitude = map['latitude'];
nearbyUsers.longitude = map['longitude'];
GeofireAssistant.nearbyAvailableUsers.add(nearbyUsers);
GeofireAssistant.updateNearbyLocation(nearbyUsers);
RequestAssistant.updateUsers();
break;
case Geofire.onGeoQueryReady:
RequestAssistant.updateUsers();
break;
}
}
if (mounted) {
setState(() {
// Your state change code goes here
});
}
});```

Unable to catch Google cloud storage exception

I have a function in my flutter app to download a file from google cloud and store it locally. This function works for existing files, but when I try to download a non existent file, it fails to catch the 'file not found' exception. I'm obviously doing something wrong, but I can't figure it out!
bool downloadFile({required String localFile, required String remoteFile}) {
try {
final storageRef = FirebaseStorage.instance.ref();
final remoteFileRef = storageRef.child(remoteFile);
final file = File(localFile);
final downloadTask = remoteFileRef.writeToFile(file);
downloadTask.snapshotEvents.listen((taskSnapshot) {
switch (taskSnapshot.state) {
case TaskState.running:
print('TaskState.running');
break;
case TaskState.paused:
print('TaskState.paused');
break;
case TaskState.success:
print('TaskState.success');
break;
case TaskState.canceled:
print('TaskState.canceled');
break;
case TaskState.error:
print('TaskState.error');
break;
}
});
//} on firebase_core.FirebaseException catch (error) {
} catch (e) {
print("########### got ex");
return false;
}
return true;
}

Amplify DataStore: How to know when sync is finished?

How can we know that DataStore has finished the sync?
When doing the first await DataStore.query(MyEntity) after the user logged in, DataStore is returning right away and not waiting for the data to be synced with the cloud.
I want to wait for the sync to be completed and put a loading when the data isn't synced yet.
make your model class observable so that it can check for data in realtime
Amplify.DataStore.observeQuery(MyEntity.classType).listen((event) {
if (event.isSynced) {//boolean value
print("Synced Successfully!");
// even you can get synced data here also
List< MyEntity> items = event.items;
} else {
//Show ProgressBar Here
print("Fetching Data From Cloud");
}
});
You can listen to events on the datastore channel with Amplify.Hub.listen.
details:
subscription = Amplify.Hub.listen([HubChannel.DataStore], (dynamic hubEvent) async {
switch (hubEvent.eventName) {
case 'networkStatus':
_amplifyIsUp.value = hubEvent.payload.active;
break;
case 'subscriptionsEstablished':
_amplifyMessage.value = 'Starting to sync from cloud...';
break;
case 'syncQueriesStarted':
_amplifyIsSyncing.value = true;
_amplifyMessage.value = 'Syncing...';
break;
case 'modelSynced':
ModelSyncedEvent mse = hubEvent.payload;
_amplifyMessage.value = '${mse.modelName} has been sync\'d from cloud...';
break;
case 'syncQueriesReady':
_amplifyMessage.value = 'Done!';
_amplifyIsSyncing.value = false;
///do your bits here
onSyncsReady.call();
break;
case 'ready':
_amplifyIsSyncing.value = false;
break;
case 'subscriptionDataProcessed':
SubscriptionDataProcessedEvent sdpe = hubEvent.payload;
_amplifyMessage.value = 'Syncing ${sdpe.element.model.classType.modelName()}...';
if (sdpe.element.model is DeviceStatus) {
DeviceStatus ds = sdpe.element.model as DeviceStatus;
if (ds.clientID == _clientService.client.id && ds.status == Status.REQUESTSTATUS) {
_statusService.performHeartbeat();
}
}
break;
case 'outboxMutationEnqueued':
_amplifyIsSyncing.value = true;
_amplifyHasDirt.value = true;
break;
case 'outboxMutationProcessed':
OutboxMutationEvent ome = hubEvent.payload;
_amplifyIsSyncing.value = false;
break;
case 'outboxStatus':
OutboxStatusEvent ose = hubEvent.payload;
if (ose.isEmpty) {
_amplifyIsSyncing.value = false;
_amplifyHasDirt.value = false;
} else {
_amplifyHasDirt.value = true;
}
break;
}
});
boop

Mirth: Evaulating SWITCH versus IF Statement

I'm using a product called Mirth (version 3.6) to execute transform code. It doesn't seem to have an interactive debugger so can anyone explain why the following code in a destination transform will only log from the IF statement and not from the SWITCH statement? Works perfectly from regular java running in Eclipse but this code is executing inside a JavaScript engine that Mirth uses (Rhino if I'm not mistaken).
for each (node in msg['PID'].children())
{
if(node.name() == "PID.3")
{
logger.info("IF Succeeded");
}
switch(node.name())
{
case "PID.3":
logger.info("SWITCH Succeeded"); // This line never logs
break;
}
}
This is a common issue with Mirth Connect since it uses Rhino as it's engine (uses java as well as javascript).
The Switch statement doesn't work with a Java String object
The simple solution is to convert any unknown string type to a native JS string by concatenating an empty string to the questionable string (i.e. str + '')
// See in action
for each (node in msg['PID'].children())
{
var nodeName = node.name();
if (nodeName != "PID.3")
{
continue;
}
var type = typeof(nodeName);
logger.debug('NodeName: ' + nodeName + '; Type: ' + type);
if (type == 'object') {
logger.debug('Type is object');
if (nodeName instanceof String) {
logger.debug('Object is Java String instance');
} else {
logger.debug('Object is not Java String instance');
}
} else if (type === 'string') {
logger.debug('Type is JS string.');
} else {
logger.debug('Type is not object or string. Type: ' + type);
}
// Works with String object or JS string
if (nodeName == "PID.3")
{
logger.info("IF Succeeded");
}
// Only works with JS string
switch (nodeName)
{
case "PID.3":
logger.info("SWITCH Succeeded"); // This line never logs
break;
default:
logger.info("SWITCH not matched: " + nodeName);
break;
}
logger.debug('Convert to JS string');
nodeName = nodeName + '';
type = typeof(nodeName);
logger.debug('Converted Type: ' + type);
if (type == 'object') {
logger.debug('Converted Type is object');
if (nodeName instanceof String) {
logger.debug('Converted Object is String instance');
} else if (nodeName instanceof string) {
logger.debug('Converted Object is string instance');
} else {
logger.debug('Converted Object is not Java String instance');
}
} else if (type === 'string') {
logger.debug('Converted Type is JS string.');
} else {
logger.debug('Converted Type is not object or string. Type: ' + type);
}
switch(nodeName)
{
case "PID.3":
logger.info("SWITCH with js string Succeeded");
break;
default:
logger.info("SWITCH with js string not matched: " + nodeName);
break;
}
break;
}

Quickest way to validate form input fields with JS

What is the quickest way to validate al my input fields with javaScript?
I want to check if the fields are filled in or not.
Thx
following is my javascript code :
<script>
function Check(frm)
{
var input, EmptyFound=false;
var elem = document.getElementById('frmMain').elements;
for(var i=0;i<elem.length;i++)
{
input = elem[i];
if(input.type == "text")
{
if(input.value == "")
{
EmptyFound = true;
break;
}
}
return notEmpty;
}
</script>
I would use jQuery Validate.
A single line of jQuery to select the form and apply the validation
plugin. And a bit of metadata on each element to specify the
validation rules.
The docs specifically for enforcing required are at
http://docs.jquery.com/Plugins/Validation/Methods/required
It requires adding jQuery (if you don't use it already) but provides a fast and powerful validation framework.
you can use this to distinguish between input different types
this is just a sample from my project
//var frm_elements = document.mainForm.elements;
//var frm_elements =document.getElementById('mainForm').elements;
for (var i = 0; i < document.mainForm.elements.length; i++)
{document.mainForm.elements[i];
if(document.mainForm.elements[i]!=null)
{
var field_type = document.mainForm.elements[i].type;
switch (field_type)
{
case "text":
if(document.mainForm.elements[i].name.indexOf("from")!='-1' &&
document.mainForm.elements[i].name.indexOf("frotom")!='-1' &&
!document.mainForm.elements[i].name.indexOf("serNo")!='-1' &&
!document.mainForm.elements[i].name.indexOf("repKey")!='-1' &&
!document.mainForm.elements[i].name.indexOf("orderKey")!='-1' &&
!document.mainForm.elements[i].name.indexOf("formatKey")!='-1' )
{
document.mainForm.elements[i].value = "";
}
break;
case "password":
case "textarea":
case "hidden":
/* frm_elements[i].value = "";
break;*/
case "radio":
case "checkbox":
/*if (frm_elements[i].checked)
{
frm_elements[i].checked = false;
}
break;*/
case "select-one":
case "select-multi":
if(document.mainForm.elements[i].name.indexOf("ddlMainSubModule")=='-1')
document.mainForm.elements[i].selectedIndex = 0;
break;
default:
break;
}
}
}