Any idea what is wrong here?
I have a function which receive data from server by a rest call, which return Future object.
Future _function(){
var future = _getWithID('path');
future.then((data) {
List<SOMEOBJECT> SOMEOBJECT = data["entities"].map((v) {
return new SOMEOBJECT(
id: v["properties"]["id"],
name: titleize(v["properties"]["name"])
);
}).toList();
return new Future.value(SOMEOBJECT.process(SOMEOBJECT));
});
}
Model class for SOMEOBJECT
class SOMEOBJECT extends Model {
int id;
String name;
SOMEOBJECT({this.id, this.name});
static Map process(List<String> SOMEOBJECTS) {
// map = {name: A, value:[{name:list<String>},{name:list<String>}]}
return map;
}
}
Cache object which try to cache in browser
class CacheManager {
Map callbacks;
Map cache;
CacheManager(this.cache){
callbacks = {};
}
Future setData(String key, Function updateFunction) {
return chrome.storage.local.get(key).then( (resp){
cache[key] = resp[key];
return updateFunction().then((data) {
chrome.storage.local.set({key: data});
cache[key] = data;
}).whenComplete( () {
handleCallbacks(key);
});
});
}
void registerCallback(String key, Function callback) {
callbacks[key] = callback;
}
void handleCallbacks(String key){
if (callbacks[key] != null){
callbacks[key](cache[key]);
}
}
}
So I have these two lines before
cacheManager.registerCallback("SOMEOBJECT", loadSomeOBJECT);
cacheManager.setData('SOMEOBJECT', api._function);
and I am getting this error:
ERROR
NoSuchMethodError: method not found: 'then'
Receiver: null
Arguments: [Closure: (dynamic) => dynamic]
#0 Object._noSuchMethod (dart:core-patch/object_patch.dart:42)
#1 Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#2 CacheManager.setData.<anonymous closure> (chrome-extension://ekfcndmmkincdeoolhcebmhcgmkmadip/helpers.dart:27:31)
#3 _RootZone.runUnary (dart:async/zone.dart:1149)
#4 _Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:551)
#5 _Future._propagateToListeners (dart:async/future_impl.dart:637)
#6 _Future._completeWithValue (dart:async/future_impl.dart:424)
#7 _Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:479)
#8 _microtaskLoop (dart:async/schedule_microtask.dart:41)
#9 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50)
#10 _ScheduleImmediateHelper._handleMutation (dart:html:49254)
#11 MutationObserver._create.<anonymous closure> (dart:html:27525)
this refer to the line which setData and callback from cache object. then the cache object will call the api.function to get the data from server, and then the raw data is served, it goes to process method in SOMEOBJECT class and return the MAP of JSON representation. Once the data back to cache manager to call the then on the future object it fails. with the error on the question. Any idea?
Thanks
I just had a brief look and saw
Future _function(){
var future = _getWithID('path');
return future.then((data) {
is missing a return. There might be other issues though.
Related
I am trying to build a flutter UI app to publish and subscribe messages over mqtt5 protocol. I am using the library mqtt5_client: ^3.3.4
Subscription works like a charm. But while publishing the library throws InvalidHeaderException. The source code is not of much help in resolving the problem.
Thanks in advance for any pointer.
The full code and exception stack trace is given below. Problem is in the publish method in the call to publish
import 'dart:io';
import 'dart:convert';
import 'package:mqtt5_client/mqtt5_client.dart';
import 'package:mqtt5_client/mqtt5_server_client.dart';
class MQTTClient {
late MqttServerClient _client;
MQTTClient(String url, String clientId, int port) {
_client = MqttServerClient(url, clientId);
_client.port = port;
_client.keepAlivePeriod = 60;
_client.onConnected = onConnected;
_client.onDisconnected = onDisconnected;
MqttConnectMessage connectMessage =
MqttConnectMessage().withWillQos(MqttQos.atLeastOnce);
_client.connectionMessage = connectMessage;
_client.logging(on: true);
}
void subscribe(String topic) {
_client.onSubscribed = onSubscribed;
_client.subscribe(topic, MqttQos.atLeastOnce);
_client.updates.listen((List<MqttReceivedMessage<MqttMessage?>>? msg) {
final recMess = msg![0].payload as MqttPublishMessage;
List<int> msgbytes = (recMess.payload.message)!.cast<int>();
print(
'Received message: topic is ${msg[0].topic}, payload is ${utf8.decode(msgbytes)} ');
});
}
void publish(String topic, String message) {
final builder = MqttPayloadBuilder();
builder.addString(message);
_client.publishMessage(topic, MqttQos.atLeastOnce, builder.payload!);
_client.published!.listen((event) {
print(
'Published topic: topic is ${event.variableHeader!.topicName}, with Qos ${event.header!.qos}');
});
}
Future<int> connect() async {
try {
await _client.connect();
} on MqttNoConnectionException catch (e) {
print('connect exception - $e');
} on SocketException catch (e) {
print('socket exception - $e');
}
if (_client.connectionStatus!.state == MqttConnectionState.connected) {
print('client connected');
} else {
print(
'client connection failed - disconnecting, status is ${_client.connectionStatus}');
_client.disconnect();
exit(-1);
}
return 0;
}
}
MqttSubscription onSubscribed(MqttSubscription subscription) {
print('subscribed $subscription');
return subscription;
}
void onConnected() {
print("client connected");
}
void onDisconnected() {
print('client disconnected');
}
The exception stacktrace is :
Unhandled exception:
mqtt-client::InvalidHeaderException: The supplied header is invalid. Header must be at least 2 bytes long.
#0 MqttHeader.readFrom (package:mqtt5_client/src/messages/mqtt_header.dart:69:7)
#1 new MqttHeader.fromByteBuffer (package:mqtt5_client/src/messages/mqtt_header.dart:19:5)
#2 MqttByteBuffer.isMessageAvailable (package:mqtt5_client/src/utility/mqtt_byte_buffer.dart:66:29)
#3 MqttServerConnection._onData (package:mqtt5_client/src/connectionhandling/server/mqtt_server_connection.dart:60:26)
#4 _RootZone.runUnaryGuarded (dart:async/zone.dart:1586:10)
#5 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
#6 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
#7 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
#8 _StreamController._add (dart:async/stream_controller.dart:648:7)
#9 _StreamController.add (dart:async/stream_controller.dart:596:5)
#10 _Socket._onData (dart:io-patch/socket_patch.dart:2324:41)
#11 _RootZone.runUnaryGuarded (dart:async/zone.dart:1586:10)
#12 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
#13 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
#14 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
#15 _StreamController._add (dart:async/stream_controller.dart:648:7)
#16 _StreamController.add (dart:async/stream_controller.dart:596:5)
#17 new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1849:33)
#18 _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1322:14)
#19 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
#20 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
#21 _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:122:13)
#22 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:193:5)
The author of this library has resolved the issue; The error is specific to mqtt5 and is under investigation. The solution is to handle|ignore the exception as this occurs after the message is published. Another option is to use mqtt_client instead of mqtt5_client. Both methods work https://github.com/shamblett/mqtt_client/issues/438#issuecomment-1378346434
I'm using flutter-sound to record (and then play back) some audio in my flutter app. However, I've run up against an interesting problem: On the iOS emulator it works, but on the actual iOS device I get an obscure error. Both are running on the same version of iOS (15.4).
Here is the code for starting and stopping the recording/playback, it's simple enough:
Future<void> startRecording(GlobalState curState) async {
setState(() {
recording = true;
});
curState.startRecording();
Directory directory = Directory(pathToAudio);
if (filePathText.isNotEmpty && File(filePathText).existsSync()) {
File(filePathText).deleteSync();
}
if (!directory.existsSync()) {
directory.createSync();
}
await _recordingSession.startRecorder(
toFile: (filePathName()),
codec: (Platform.isIOS ? Codec.pcm16WAV : Codec.aacMP4),
audioSource: AudioSource.microphone,
);
}
Future<void> stopRecording(GlobalState curState) async {
setState(() {
recording = false;
});
String? fileURL = await _recordingSession.stopRecorder();
print("the file is recorded!!!");
print("FILEPATH:");
print(fileURL);
curState.stopRecording();
if (fileURL != null) {
filePathText = fileURL;
if (widget.widgetControlInfo.onChanged != null) {
FileAnswer tempA = FileAnswer.fromBasicQuestion(widget.currentQuestion);
tempA.filePath = fileURL;
tempA.filetype = FileType.recording;
if (widget.widgetControlInfo.onChanged != null) {
widget.widgetControlInfo.onChanged!(tempA);
}
}
} else {
print('sumn went rong wit da recording');
}
}
String filePathName() =>
pathToAudio +
DateTime.now().month.toString() +
DateTime.now().day.toString() +
DateTime.now().hour.toString() +
DateTime.now().minute.toString() +
DateTime.now().second.toString() +
(Platform.isIOS ? ".wav" : ".m4a");
Future<void> playControl() async {
if (playing) {
await stopPlaying();
} else {
await startPlaying();
}
}
Future<void> startPlaying() async {
setState(() {
playing = true;
});
if (filePathText.isEmpty) {
return;
} else {
if (File(filePathText).existsSync()) {
print("the file existssss!!!");
print("FILEPATH:");
print(filePathText);
}
await _playingSession.startPlayer(
fromURI: filePathText,
codec: (Platform.isIOS ? Codec.pcm16WAV : Codec.aacMP4),
whenFinished: () {
print("its over");
stopPlaying();
});
}
return;
}
Future<void> stopPlaying() async {
setState(() {
playing = false;
});
await _playingSession.stopPlayer();
}
void _initializer() async {
if (Platform.isIOS) {
var directory = await getTemporaryDirectory();
print("TIS IOS");
pathToAudio = directory.path + '/';
} else {
pathToAudio = '/sdcard/Download/m-Path/';
}
_recordingSession = new FlutterSoundRecorder(logLevel: Level.debug);
_playingSession = new FlutterSoundPlayer(logLevel: Level.debug);
await _recordingSession.openRecorder();
await _playingSession.openPlayer();
await _recordingSession
.setSubscriptionDuration(Duration(milliseconds: 10))
.then((value) => null);
_recorderSubscription = _recordingSession.onProgress!.listen((e) {
setState(() {
_timerText = e.duration.toString().substring(0, 10);
});
});
await _playingSession.setSubscriptionDuration(Duration(milliseconds: 10));
_playerSubscription = _playingSession.onProgress!.listen((e) {
setState(() {
_timerText = e.position.toString().substring(0, 10);
});
});
await Permission.microphone.request();
await Permission.storage.request();
await Permission.manageExternalStorage.request();
}
Here's what the UI portion looks like. On the iOS emulator, when I press the recording button, the timer starts incrementing, and after I press it again, I can press the play button to listen what I just recorded. On the device, when I press the button, the timer doesn't increment but stays at zero, and when I try to play the audio, I get the following error:
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: PlatformException(Audio Player, startPlayer failure, null, null)
#0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
#1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:177:18)
<asynchronous suspension>
#2 MethodChannelFlutterSoundPlayer.invokeMethod (package:flutter_sound_platform_interface/method_channel_flutter_sound_player.dart:157:12)
<asynchronous suspension>
#3 FlutterSoundPlayer._startPlayer (package:flutter_sound/public/flutter_sound_player.dart:819:19)
<asynchronous suspension>
#4 FlutterSoundPlayer.startPlayer.<anonymous closure> (package:flutter_sound/public/flutter_sound_player.dart:759:11)
<asynchronous suspension>
#5 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16)
<asynchronous suspension>
#6 FlutterSoundPlayer.startPlayer (package:flutter_sound/public/flutter_sound_player.dart:758:5)
<asynchronous suspension>
#7 _RecordingQuestionWidgetS.startPlaying (package:flutter_app2/interactions/widgets/questionWidgets/RecordingQuestionWidget.dart:216:7)
<asynchronous suspension>
#8 _RecordingQuestionWidgetS.playControl (package:flutter_app2/interactions/widgets/questionWidgets/RecordingQuestionWidget.dart:200:7)
<asynchronous suspension>
I asked the flutter-sound author on github already, but it seems he doesn't really know what's wrong either, and the fact that it works on the simulator but not on the device makes me think the problem might be larger than just some faulty code.
A different part of the same app already saves and shows saved images from the same directory so I don't think it's a permission issue.
Apparently, on iOS, this doesn't work unless you create an AudioSession instance (from this package). The new initializer function looks like this:
void _initializer() async {
if (Platform.isIOS) {
var directory = await getApplicationDocumentsDirectory();
pathToAudio = directory.path + '/';
} else {
pathToAudio = '/sdcard/Download/appname/';
}
_recordingSession = new FlutterSoundRecorder();
_playingSession = new FlutterSoundPlayer();
await _recordingSession.openRecorder();
await _playingSession.openPlayer();
final session = await AudioSession.instance;
await session.configure(AudioSessionConfiguration(
avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
avAudioSessionCategoryOptions:
AVAudioSessionCategoryOptions.allowBluetooth |
AVAudioSessionCategoryOptions.defaultToSpeaker,
avAudioSessionMode: AVAudioSessionMode.spokenAudio,
avAudioSessionRouteSharingPolicy:
AVAudioSessionRouteSharingPolicy.defaultPolicy,
avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
androidAudioAttributes: const AndroidAudioAttributes(
contentType: AndroidAudioContentType.speech,
flags: AndroidAudioFlags.none,
usage: AndroidAudioUsage.voiceCommunication,
),
androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
androidWillPauseWhenDucked: true,
));
await _recordingSession
.setSubscriptionDuration(Duration(milliseconds: 10))
.then((value) => null);
_recorderSubscription = _recordingSession.onProgress!.listen((e) {
setState(() {
_timerText = e.duration.toString().substring(0, 10);
});
});
await _playingSession.setSubscriptionDuration(Duration(milliseconds:
10));
_playerSubscription = _playingSession.onProgress!.listen((e) {
setState(() {
_timerText = e.position.toString().substring(0, 10);
});
});
await Permission.microphone.request();
await Permission.storage.request();
await Permission.manageExternalStorage.request();
}
I'm confusing in how to set an image as wallpaper in flutter, I have tried to use this code below reference from here!
my flutter code:
in this code, I tried to make file from URL
//get URL image and save it and create a file
_setWallp(String imageUrl) async {
try {
var httpClient = http.Client();
var list = await httpClient.readBytes(imageUrl);
final tempDir = await getTemporaryDirectory();
final file = await new Io.File('${tempDir.path}/image.jpg').create();
file.writeAsBytes(list);
final channel = const MethodChannel('setwallpaper');
channel.invokeMethod('shareFile', 'image.jpg');
} catch (e) {
print('Share Error :$e');
}
}
my java code :
in this java code, I tried to set bitmap as wallpaper from file path that I created in flutter
//call method channel from flutter
private static final String SHARE_CHANNEL = "setwallpaper";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(this.getFlutterView(), SHARE_CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
public final void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("shareFile")) {
shareFile((String) methodCall.arguments);
}
}
});
}
private void shareFile(String path) {
File imgFile = new File(this.getApplicationContext().getCacheDir(), path);
// set bitmap to wallpaper
Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
WallpaperManager wm = WallpaperManager.getInstance(this);
try{
wm.setBitmap(bitmap);
}catch (IOException e){
Log.e(TAG, "shareFile: cannot set image as wallpaper",e );
}
}
}
debug console message:
//message from console
E/flutter (10376): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (10376): PlatformException(error, Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference, null)
E/flutter (10376): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:547:7)
E/flutter (10376): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:279:18)
E/flutter (10376): <asynchronous suspension>
E/flutter (10376): #2 FullScreenState._setWallp (file:///D:/fltr/cat_wallpapers/lib/fullscreen.dart:111:15)
E/flutter (10376): <asynchronous suspension>
E/flutter (10376): #3 FullScreenState.build.<anonymous closure> (file:///D:/fltr/cat_wallpapers/lib/fullscreen.dart:71:31)
E/flutter (10376): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:494:14)
E/flutter (10376): #5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:549:30)
E/flutter (10376): #6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
E/flutter (10376): #7 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:161:9)
E/flutter (10376): #8 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:94:7)
E/flutter (10376): #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9)
E/flutter (10376): #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
E/flutter (10376): #11 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
E/flutter (10376): #12 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:143:19)
E/flutter (10376): #13 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:121:22)
E/flutter (10376): #14 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:101:7)
E/flutter (10376): #15 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:64:7)
E/flutter (10376): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:48:7)
E/flutter (10376): #17 _invoke1 (dart:ui/hooks.dart:134:13)
E/flutter (10376): #18 _dispatchPointerDataPacket (dart:ui/hooks.dart:91:5)
D/EGL_emulation(10376): eglMakeCurrent: 0xb429e760: ver 2 0
I/FlutterActivityDelegate(10376): onResume setting current activity to this
D/EGL_emulation(10376): eglCreateContext: 0xb429e820: maj 2 min 0 rcv 2
D/EGL_emulation(10376): eglMakeCurrent: 0xb429e820: ver 2 0
D/EGL_emulation(10376): eglMakeCurrent: 0xb429e760: ver 2 0
D/EGL_emulation(10376): eglMakeCurrent: 0xb429e820: ver 2 0
I/flutter (10376): Another exception was thrown: type 'Future<dynamic>' is not a subtype of type 'Future<File>' //didn't understand about this
need help.. thank you
Using Dio library...Make Sure That First You Download The Image And Once Downloaded Set As Wallpaper
Future<Null> setWallpaper() async {
Dio dio = Dio();
try {
var dir = await getTemporaryDirectory();
await dio.download(widget.img, "${dir.path}/myimage.jpeg",
onProgress: (rec, total) {
setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
print(progressString);
if (progressString == "100%") {
_setWallpaer();
}
});
});
} catch (e) {}
setState(() {
downloading = false;
progressString = "Completed";
});}
Future<Null> _setWallpaer() async {
String setWallpaper;
try {
final int result =
await platform.invokeMethod('setWallpaper', 'myimage.jpeg');
setWallpaper = 'Wallpaer Updated....';
} on PlatformException catch (e) {
setWallpaper = "Failed to Set Wallpaer: '${e.message}'.";
}
setState(() {
_setWallpaper = setWallpaper;
});}
You Can See Full Source Code If It Can Help.....
https://github.com/pratiktimer/flutterwallpaper
Here error is created due to the Methodchannel invokemethod. So, this is solved in
Wallpaper plugin. Which can be use for Setting Wallpaper.
onPressed: () async {
try {
// path_provider: any
// async_wallpaper: any
// import 'package:async_wallpaper/async_wallpaper.dart';
// import 'package:path_provider/path_provider.dart';
// import 'package:flutter/services.dart';
// import 'dart:io';
ByteData imagebyte = await rootBundle
.load('assets/images/kissing_image_real.png');
final temp = await getTemporaryDirectory();
final path = '${temp.path}/image1.jpg';
File(path).writeAsBytesSync(imagebyte.buffer.asUint8List());
AsyncWallpaper.setWallpaperFromFile(
path, AsyncWallpaper.HOME_SCREEN)
.whenComplete(() {
ProgressBar.stop();
Get.snackbar('Success', 'New Wallpaper set',
colorText: Colors.white);
});
} catch (e) {
}
},
I asked to fix an issue in software which use dart to develop a chrome application. currently, the chrome application doesn't run in my mac osx and I get the following exception:
Uncaught Unhandled exception:
Class '_InternalLinkedHashMap' has no instance method 'pushState'.
NoSuchMethodError: method not found: 'pushState'
Receiver: _LinkedHashMap len:0
Arguments: [null, "", "/index.html#events"]
#0 Object._noSuchMethod (dart:core-patch/object_patch.dart:42)
#1 Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#2 Router._go (package:route/client.dart:153:22)
#3 Router.gotoPath (package:route/client.dart:139:7)
#4 Router.listen.<anonymous closure> (package:route/client.dart:111:13)
#5 wrap_event_listener.<anonymous closure>.<anonymous closure> (dart:html:1189)VM81:1 (anonymous function)
After I backtrace the issue, I found that listen() function instead of calling handle calls gotoPath(string,string). Can someone explain me that. this cause
[https://github.com/justinfagnani/route/blob/master/lib/client.dart][1]
void gotoPath(String path, String title) {
_logger.finest('gotoPath $path');
var url = _getUrl(path);
if (url != null) {
_go(path, title);
// If useFragment, onHashChange will call handle for us.
if (!_listen || !useFragment) {
_handlers[url](path);
}
}
}
void handle(String path) {
_logger.finest('handle $path');
var url = _getUrl(path);
if (url != null) {
// always give handlers a non-fragment path
var fixedPath = url.reverse(url.parse(path));
_handlers[url](fixedPath);
} else {
_logger.info("Unhandled path: $path");
}
}
this calls from here:
Note that other methods if/else call handle and only the !ignoreclick is call gotopath
void listen({bool ignoreClick: false}) {
_logger.finest('listen ignoreClick=$ignoreClick useFragment=$useFragment');
if (_listen) {
throw new StateError('listen should be called once.');
}
_listen = true;
if (useFragment) {
window.onHashChange.listen((_) {
var path = '${window.location.pathname}${window.location.hash}';
_logger.finest('onHashChange handle($path)');
return handle(path);
});
handle('${window.location.pathname}${window.location.hash}');
} else {
window.onPopState.listen((_) {
var path = '${window.location.pathname}${window.location.hash}';
_logger.finest('onPopState handle($path)');
handle(path);
});
}
if (!ignoreClick) {
window.onClick.listen((e) {
if (e.target is AnchorElement) {
AnchorElement anchor = e.target;
if (anchor.host == window.location.host) {
var fragment = (anchor.hash == '') ? '' : '${anchor.hash}';
gotoPath("${anchor.pathname}$fragment", anchor.title);
e.preventDefault();
}
}
});
}
}
Dart test code:
_doSomething2(callback(int x, int y)) {
callback(1, 2);
}
test('async test, check a function with 2 parameters', () {
new Timer(new Duration(milliseconds:100), _doSomething2(expectAsync2((x, y) {
expect(x, equals(1));
expect(y, equals(2));
})));
});
When I run it in Intellij-IDEA as "unittest", it passed, but there is some error message shown:
Testing started at PM11:08 ...
Unhandled exception:
The null object does not have a method 'call'.
NoSuchMethodError : method not found: 'call'
Receiver: null
Arguments: []
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1 _createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:11)
#2 _handleTimeout (timer_impl.dart:283)
#3 _handleTimeout (timer_impl.dart:292)
#4 _handleTimeout (timer_impl.dart:292)
#5 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:115)
Process finished with exit code 255
Where is wrong?
The test ends before the code inside the new Timer() is executed.
void main(List<String> args) {
test('async test, check a function with 2 parameters', () {
var callback = expectAsync0(() {});
new Timer(new Duration(milliseconds:100), () {
_doSomething2((x, y) {
expect(x, equals(1));
expect(y, equals(2));
callback();
});
});
});
}
This way the test doesn't end until callback is called.