Hi I cant seem to find the right way to simulate keyevents, I have come across 3 differend options I tried but none of them did work for me.
//V1
import 'dart:async';
import 'dart:html';
void main() {
var stream = KeyEvent.keyPressEvent.forTarget(document.body);
stream.listen((KeyEvent keyEvent){
if(keyEvent.keyCode == KeyCode.ESC) {
// do stuff
}
});
stream.add(new KeyEvent('keypress', keyCode: KeyCode.ESC));
}
-
//V2
import 'dart:html';
myCustomKeyHandler(KeyEvent e) {
print('The charCode is ${e.charCode}');
print('The keyCode is ${e.keyCode}');
}
main() {
var controller = new KeyboardEventController.keydown(document.window);
controller.add(myCustomKeyHandler);
}
-
//V3
import 'dart:html';
myCustomKeyHandler(KeyboardEvent e) {
print('The charCode is ${e.charCode}');
print('The keyCode is ${e.keyCode}');
}
main() {
document.window.add(myCustomKeyHandler, false);
}
the best I get is
Uncaught InvalidStateError: Failed to execute 'dispatchEvent' on 'EventTarget': The event is already being dispatched.
sources
https://github.com/dart-lang/sdk/issues/17950
How to dispatch an KeyboardEvent with specific KeyCode
https://groups.google.com/a/dartlang.org/forum/#!topic/misc/mgnd1TUGn68
Related
When adding async* to listen method it isn't executing the function body
import 'dart:async';
main(List<String> args) {
print('====');
tranStream();
}
Stream<int> intStreamer() async* {
int c = 0;
while (c <= 30) {
await Future.delayed(Duration(seconds: 1));
yield c++;
}
}
tranStream() {
intStreamer().listen((event) async* { // If i remove async* from here it will execute print statement
print(event);
});
}
If i remove async* from intStreamer().listen it will execute print statement. What is happening here?
When you are using async*, the method will only start being executed when the returned Stream gets a subscriber. Your code does not really make any sense since listen takes a method which returns void. So nobody are going to listen on the returned Stream which the given method will automatically return (based on the async* keyword).
I would also properly rewrite your code so you instead of listen uses await for which I think makes it more clear what happens`:
import 'dart:async';
Future<void> main(List<String> args) async {
print('====');
await tranStream();
}
Stream<int> intStreamer() async* {
int c = 0;
while (c <= 30) {
await Future<void>.delayed(const Duration(seconds: 1));
yield c++;
}
}
Future<void> tranStream() async {
await for (final event in intStreamer()) {
print(event);
}
}
Update with example of tranStream returns a Stream:
import 'dart:async';
Future<void> main(List<String> args) async {
print('====');
await for (final event in tranStream()) {
print('main got: $event');
}
}
Stream<int> intStreamer() async* {
int c = 0;
while (c <= 30) {
await Future<void>.delayed(const Duration(seconds: 1));
yield c++;
}
}
Stream<int> tranStream() async* {
await for (final event in intStreamer()) {
print('tranStream got: $event');
yield event;
}
}
import 'dart:io';
void main() {
performTask();
}
void performTask() {
task1();
task2();
task3();
}
void task1() {
print('task1');
}
void task2() {
Duration timeDuration = Duration(seconds: 3);
sleep(timeDuration);
print('task2');
}
void task3() {
print('task3');
}
After executing first function that is task1() it throws an error:
Uncaught Error: Unsupported operation: ProcessUtils._sleep
I just hit the same roadblock! Not sure how to get sleep to work, but i found that using async/await is a bit more predictable:
// Unused import
// import 'dart:io'; // Delete me
void main() {
performTask();
}
// No need for async/await here, just the method in which it's used to await Future.delayed
void performTask() {
task1();
task2();
task3();
}
void task1() {
print('task1');
}
// I'm still a bit new to flutter, but as I understand it, best practice is to use Future<T> myFunction() {...} when defining async/await method.
// In this case <T> is <void> because you're not returning anything!
Future<void> task2() async {
Duration timeDuration = Duration(seconds: 3);
// sleep(timeDuration) // Delete Me
await Future.duration(timeDuration); // replacement for the sleep method, comes from the 'package:flutter/material.dart'
print('task2');
}
void task3() {
print('task3');
}
Credit: How can I "sleep" a Dart program
Since Future.duration doesn't
await Future.delayed(const Duration(seconds: 1));
credit: How can I "sleep" a Dart program
I'm trying to make a global click event directive. But document:click does not work for me.
import 'package:angular/angular.dart';
#Directive(
selector: '[clickOutside]'
)
class ClickOutsideDirective {
#HostListener('click', [r'$event.target'])
void onClick(targetElement){
print('Target:' + targetElement.toString());
}
}
When changing document:click to click I get expected behavior. But of course not globally. What am I doing wrong?
The document: and similar event scopes were removed in Dart.
Use instead
import 'dart:html';
class ClickOutsideDirective implements OnInit, OnDestroy {
StreamSubscription _docClickSub;
ngOnInit() {
_docClickSub = document.onClick.listen((event) {
print('Target:' + event.target.toString());
});
}
ngOnDestroy() {
_docClickSub?.cancel();
_docClickSub = null;
}
}
I want to create a random sound sequencer, just for learning more about WebAudio and Dart.
My idea is to load some sound examples and play them in random order endlessly.
For that, I've loaded all the files, decoded them in a arraybuffer and put them to play with the following function:
void startAudio()
{
int index=random.nextInt(buffers.length);
print("Audio played [${index}].");
source.buffer=buffers[index];
source.connect(context.destination, 0, 0);
source.start(0);
Timer timer=new Timer(100, this.proceed);
}
void proceed(Timer timer)
{
this.startAudio();
}
The problem is that after some time, the sounds stop playing.
What is going wrong?
Is it the best way to do what I'm trying to do?
If someone wants to test my code, here is the link:
http://cg.usr.sh/Dart/WebAudioTest/WebAudioTest.html
After randomly changing things, I got it working as I was expecting.
import 'dart:html';
import 'dart:math';
import 'dart:async';
class AudioMaker
{
List<String> urls;
AudioContext context;
List<AudioBuffer> buffers;
Random random;
AudioMaker()
{
this.urls=new List<String>();
this.context=new AudioContext();
this.buffers=new List<AudioBuffer>();
this.random=new Random(0);
}
void checkAndStart()
{
if(buffers.length == urls.length)
{
Timer timer=new Timer.repeating(500, this.startAudio);
}
}
void startAudio(Timer timer)
{
int index=random.nextInt(this.buffers.length);
print("Audio played [${index}].");
AudioBufferSourceNode source=context.createBufferSource();
source.buffer=this.buffers[index];
source.connect(context.destination, 0, 0);
source.start(0);
}
void _decodeAudio(url)
{
HttpRequest hr=new HttpRequest.get(url, (req){
this.context.decodeAudioData(req.response, (audio_buff)
{
print("${url} decoded.");
this.buffers.add(audio_buff);
checkAndStart();
}, (evt)
{
print("Error");
});
});
hr.responseType="arraybuffer";
}
void loadAndStart()
{
for(String url in this.urls)
{
this._decodeAudio(url);
}
}
}
main()
{
AudioMaker audioMaker=new AudioMaker();
audioMaker.urls.add("bark.ogg");
audioMaker.urls.add("drip.ogg");
audioMaker.urls.add("glass.ogg");
audioMaker.urls.add("sonar.ogg");
audioMaker.loadAndStart();
}
I am trying to scan QR code with my code. My code is running fine with 5.0(Bold) and 7.1(Torch) OS phones. It is running fine with 7.1 and 5.0. but giving problem while running with 6.0 OS(Bold 9700). The problem is - "While trying to scan QR code, app scans the QR code but camera screen doesn't pop and it remains at the front. Event it is not able to hide by using Esc key". please help me to resolve the issue with os6.
Edit:
Code while opening camera screen for QR code scan:
Hashtable hints = new Hashtable();
// The first thing going in is a list of formats. We could look for
// more than one at a time, but it's much slower.
Vector formats = new Vector();
formats.addElement(BarcodeFormat.QR_CODE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, formats);
// We will also use the "TRY_HARDER" flag to make sure we get an
// accurate scan
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
// We create a new decoder using those hints
BarcodeDecoder decoder = new BarcodeDecoder(hints);
// Finally we can create the actual scanner with a decoder and a
// listener that will handle the data stored in the QR code. We put
// that in our view screen to handle the display.
try {
_scanner = new BarcodeScanner(decoder, new LeadQRcodeDecoderListener());
_QRcodeScreen = new LeadQRcodeScannerViewScreen(_scanner);
// If we get here, all the QR code scanning infrastructure should be set
// up, so all we have to do is start the scan and display the viewfinder
_scanner.startScan();
UiApplication.getUiApplication().pushScreen(_QRcodeScreen);
}
catch (Exception e) {
e.printStackTrace();
return;
}
code for closing screen is:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().popScreen(_QRcodeScreen);
}
});
I am calling this code after scanning of QR code.
This is a problem with OS6 in some devices that has been asked before on this site. Last one was two days ago:
Blackberry OS6 camera wont shut down after capture
AFAIK there's no API to close the camera app, so it has to be done with key injection hacks, that are tricky because they need accurate timing and as CPUs are different in some models, and also because the camera app has a different design in some OSes.
So either you use JSR135 and use a renamed Zxing package to provide a camera view contained in your app, or just follow your approach but instead of closing the camera app you just bring to foreground your own app.
I have solved my same issue for os 6. After scanning of QR code, close all player and scanner connection.
You can use-
if (_scanner != null && _scanner.getPlayer() != null) {
_scanner.getPlayer().close();
}
It is helpful to me.
This will definitely help you.
here is my code , it's working perfectly in OS 6.0 device 9830
/**
* First Invoke the QR Scanner
*/
ViewFinderScreen _viewFinderScreen =
new ViewFinderScreen(ShoopingCartScreen.this); // ShoopingCartScreen.this Current Screen Object
UiApplication.getUiApplication().pushScreen(_viewFinderScreen);
package com.application.qrScanner;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
import net.rim.device.api.barcodelib.BarcodeDecoder;
import net.rim.device.api.barcodelib.BarcodeDecoderListener;
import net.rim.device.api.barcodelib.BarcodeScanner;
import net.rim.device.api.io.Base64InputStream;
import net.rim.device.api.io.http.HttpDateParser;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Keypad;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.container.MainScreen;
import com.application.data.ShoopingCartObj;
import com.application.global.Global;
import com.application.log.Log;
import com.application.main.MessageScreen;
import com.application.main.orderDetail.orderSection.InputPopUpScreen;
import com.application.main.shoopingSection.ShoopingCartScreen;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
public class ViewFinderScreen extends MainScreen
{
private BarcodeScanner _scanner;
private short _frequency = 1046;
private short _duration = 200;
private int _volume = 100;
private VideoControl vc;
private ButtonField _btnCancel;
private ShoopingCartScreen _shoopingCartScreen;
/**
* Creates a new ViewFinderScreen object
*/
public ViewFinderScreen(ShoopingCartScreen _shoopingCartScreen)
{
this._shoopingCartScreen = _shoopingCartScreen;
_btnCancel = new ButtonField("Cancel" , ButtonField.USE_ALL_WIDTH)
{
protected boolean navigationClick(int status, int time)
{
fieldChangeNotify(1);
return true;
}
};
_btnCancel.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
stopScan();
UiApplication.getUiApplication().popScreen(ViewFinderScreen.this);
}
});
// Initialize Hashtable used to inform the scanner how to
// recognize the QR code format.
Hashtable hints = new Hashtable();
Vector formats = new Vector(1);
formats.addElement(BarcodeFormat.QR_CODE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, formats);
// Initialize the BarcodeDecoder
BarcodeDecoder decoder = new BarcodeDecoder(hints);
// Create a custom instance of a BarcodeDecoderListener to pop the
// screen and display results when a QR code is recognized.
BarcodeDecoderListener decoderListener = new BarcodeDecoderListener()
{
/**
* #see BarcodeDecoderListener#barcodeDecoded(String)
*/
public void barcodeDecoded(String rawText)
{
try {
String encoded = rawText;
byte[] decoded = Base64InputStream.decode( encoded );
rawText = new String(decoded);
System.out.println( new String( decoded ) );
}
catch (Throwable t) {
System.out.println( "Unable to decode string: " + t.getMessage() );
}
displayMessage(rawText);
ViewFinderScreen.this. _shoopingCartScreen.beep();
}
};
try
{
// Initialize the BarcodeScanner object and add the associated
// view finder.
_scanner = new BarcodeScanner(decoder, decoderListener);
vc = _scanner.getVideoControl();
vc.setDisplayFullScreen(true);
add(_scanner.getViewfinder());
setStatus(_btnCancel);
}
catch(Exception e)
{
displayMessage("Initilize Scanner: " + e.getMessage());
}
startScan();
}
/**
* Informs the BarcodeScanner that it should begin scanning for QR Codes
*/
public void startScan()
{
try
{
_scanner.startScan();
}
catch(MediaException me)
{
displayMessage(" Start Scan Error: " + me.getMessage());
}
}
public void stopScan()
{
try
{
Player p = _scanner.getPlayer() ;
if(p != null)
{
p.stop();
p.deallocate();
p.close();
}
}
catch (Exception e)
{
MessageScreen.msgDialog("Exception in Stop Scanning "+e.toString());
}
}
/**
* Pops the ViewFinderScreen and displays text on the main screen
*
* #param text Text to display on the screen
*/
private void displayMessage(final String text)
{
Log.d("QR Code String ", text);
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
stopScan();
}
});
}
protected boolean keyDown(int keycode, int time)
{
if (Keypad.key(keycode) == Keypad.KEY_ESCAPE)
{
stopScan();
return true;
}
return super.keyDown(keycode, time);
}
}