I read about Zone and have used Futures in many languages. I know about Event Loop and that Dart is single threaded. However, when I write following code I could not differentiate how differently it will work and when to use one over another.
What is the difference between zone and future?
For example here:
runZoned(() async {
// Do Something
}, onError: (e, stackTrace) {
print(e);
});
Vs
someAsyncCall().catchError((e) {
print(e);
});
Futures error handling
Zones
What is a Future
Edit 1: I used runZonedGuarded instaed runZoned because runZoned.onError is deprecated.
Flutter : 'onError' is deprecated on runZoned function
Hi! With runZoned you can basically Handling asynchronous errors that are commonly caused by futures (http request, etc). The concept is similar to a try-catch in synchronous code. With Future you cannot do that.
runZoned example:
runZonedGuarded(() {
_timerError();
}, (error, stack) {
print('Uncaught error runZoneGuard: $error');
});
resullt:
I/flutter (13567): Uncaught error runZoneGuard: asynchronous error
Future example:
someCall().then((value) {
_timerError();
}, onError: (value) {
print('Uncaught error onError: $value');
}).catchError((e) {
print('Uncaught error catchError: $e');
});
result:
E/flutter (13567): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: asynchronous error
E/flutter (13567): #0 _MyHomePageState._timerError.<anonymous closure> (package:async_study/main.dart:60:7)
E/flutter (13567): #1 _rootRun (dart:async/zone.dart:1418:47)
E/flutter (13567): #2 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter (13567): #3 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter (13567): #4 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter (13567): #5 _rootRun (dart:async/zone.dart:1426:13)
E/flutter (13567): #6 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter (13567): #7 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1260:23)
E/flutter (13567): #8 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (13567): #9 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter (13567): #10 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter (13567): #11 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
And the '_timerError()' method used to trhow a async error:
void _timerError() {
Timer.run(() {
throw "asynchronous error";
});
}
Related
Here is a simple example of my problem:
import 'dart:async';
void main() {
try {
Timer(Duration(seconds: 1), () {
throw TimeoutException('1 second has expired');
});
} catch (o) {
print("caught ${o.runtimeType}");
}
}
I imagine the problem is that the timer finishes counting down after the try-catch block terminates, considering that the countdown is asynchronous and initializing the Timer was successful. How can I catch the exception without changing the callback function of the Timer?
In my specific case, I am using flutter_blue and having trouble with the async method BluetoothDevice#connect().
/// Establishes a connection to the Bluetooth Device.
Future<void> connect({
Duration? timeout,
bool autoConnect = true,
}) async {
var request = protos.ConnectRequest.create()
..remoteId = id.toString()
..androidAutoConnect = autoConnect;
Timer? timer;
if (timeout != null) {
timer = Timer(timeout, () {
disconnect();
throw TimeoutException('Failed to connect in time.', timeout);
});
}
await FlutterBlue.instance._channel
.invokeMethod('connect', request.writeToBuffer());
await state.firstWhere((s) => s == BluetoothDeviceState.connected);
timer?.cancel();
return;
}
I called the method like so:
try {
await (device as BluetoothDevice).connect(timeout: Duration(seconds: 1));
} catch (o) {
print("caught ${o.runtimeType}");
}
Considering I wait for BluetoothDevice#connect() with await and timer is cancelled upon a successful connection (at the end of the method) with timer?.cancel();, I do not know why the try-catch is not catching the following TimeoutException:
E/flutter ( 3710): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: TimeoutException after 0:00:01.000000: Failed to connect in time.
E/flutter ( 3710): #0 BluetoothDevice.connect.<anonymous closure> (package:flutter_blue/src/bluetooth_device.dart:33:9)
E/flutter ( 3710): #1 _rootRun (dart:async/zone.dart:1346:47)
E/flutter ( 3710): #2 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter ( 3710): #3 _CustomZone.runGuarded (dart:async/zone.dart:1162:7)
E/flutter ( 3710): #4 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1202:23)
E/flutter ( 3710): #5 _rootRun (dart:async/zone.dart:1354:13)
E/flutter ( 3710): #6 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter ( 3710): #7 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1186:23)
E/flutter ( 3710): #8 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter ( 3710): #9 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:395:19)
E/flutter ( 3710): #10 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:426:5)
E/flutter ( 3710): #11 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter ( 3710):
I see that the stack trace starts at BluetoothDevice#connect(), but I am not sure what to do about it.
I also tried calling then((_) {}, (o) => print("caught ${o.runtimeType}")) on the Future<void> returned by BluetoothDevice#connect() and then waiting for it inside the try-catch, yet I had no success.
Any ideas?
That connect method from the package you're using is poorly written. You're not doing anything wrong, whoever wrote that code did. If you poke around the GitHub Issues sections of that repository you'll find quite a few issues and pull requests related to this problem like this and the issues/PR it links.
The code in a timer callback exists outside of the function where the timer is instantiated. It's impossible to directly catch an error thrown in a timer callback.
If you want a timeout, don't use the functionality provided by this package, use the native Dart timeout function.
try {
await (device as BluetoothDevice).connect().timeout(Duration(seconds: 1));
} catch (o) {
print("caught ${o.runtimeType}");
}
I can't catch the exception. Has anyone known how to catch it?
This is where is the error is been throwing. I just wrapped it with a try-catch block but it's not helping me, its cant catch it and I don't know what it's a cant catch
This method is coming from my custom BaseDB abstract class and this method is overridden on my custom FirebaseDBService class.
#override
Stream<Oyuncu> oyuncuStream(String UID) {
try {
return usersColRef
.doc(UID)
.withConverter<Oyuncu>(
fromFirestore: (snapshot, _) => Oyuncu.fromJson(snapshot.data()!),
toFirestore: (Oyuncu model, _) => model.toJson(),
)
.snapshots()
.map((event) {
// if (event.data() is Map<String, dynamic>) {
// var jsonDoc = event.data() as Map<String, dynamic>;
// return Oyuncu.fromJson(jsonDoc);
if(event.data() is Oyuncu) {
return event.data() as Oyuncu;
}else{
throw Exception('Unable get user from DB');
}
});
} on Exception catch (e) {
print("Test "+e.toString());
rethrow;
}
}
My debug console:
W/ProviderInstaller(16484): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
E/flutter (16484): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Exception: Unable get user from DB
E/flutter (16484): #0 FirestoreDBService.oyuncuStream.<anonymous closure> (package:p763_quiz/data/service/db/firestoreDBService.dart:41:11)
E/flutter (16484): #1 _MapStream._handleData (dart:async/stream_pipe.dart:213:31)
E/flutter (16484): #2 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (16484): #3 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (16484): #4 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (16484): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (16484): #6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter (16484): #7 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (16484): #8 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)
E/flutter (16484): #9 _MapStream._handleData (dart:async/stream_pipe.dart:218:10)
E/flutter (16484): #10 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (16484): #11 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (16484): #12 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (16484): #13 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (16484): #14 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter (16484): #15 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (16484): #16 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)
E/flutter (16484): #17 _MapStream._handleData (dart:async/stream_pipe.dart:218:10)
E/flutter (16484): #18 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (16484): #19 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (16484): #20 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (16484): #21 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (16484): #22 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter (16484): #23 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
E/flutter (16484): #24 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:706:11)
E/flutter (16484): #25 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:663:7)
E/flutter (16484): #26 _rootRun (dart:async/zone.dart:1346:47)
E/flutter (16484): #27 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (16484): #28 _CustomZone.runGuarded (dart:async/zone.dart:1162:7)
E/flutter (16484): #29 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1202:23)
E/flutter (16484): #30 _rootRun (dart:async/zone.dart:1354:13)
E/flutter (16484): #31 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (16484): #32 _CustomZone.runGuarded (dart:async/zone.dart:1162:7)
E/flutter (16484): #33 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1202:23)
E/flutter (16484): #34 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter (16484): #35 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter (16484):
W/IInputConnectionWrapper(16484): getExtractedText on inactive InputConnection
W/IInputConnectionWrapper(16484): getTextBeforeCursor on inactive InputConnection
W/oidim.p763_qui(16484): Accessing hidden method Ldalvik/system/CloseGuard;->warnIfOpen()V (greylist,core-platform-api, linking, allowed)
The problem might be the keyword 'rethrow'. Because if you add this keyword, you will send the exceptions caught by oyuncuStream to the function where oyuncuStream was called.
--> oyuncuStream should also be wrapped with try-cat where it is called.
Successfully handled the error with the onError option.
#override
Stream<Oyuncu> oyuncuStream(String UID) {
return usersColRef
.doc(UID)
.withConverter<Oyuncu>(
fromFirestore: (snapshot, _) => Oyuncu.fromJson(snapshot.data()!),
toFirestore: (Oyuncu model, _) => model.toJson(),
)
.snapshots()
.map((event) => event.data() as Oyuncu).handleError((x){
throw 'There is a problem with your account';
});
}
I can get it from the caller.
void startListeningOyuncu(String id) {
oyuncuDBSubs = db.oyuncuStream(id).listen((oyuncu) {
emit(AuthState.auhtenticated(oyuncu));
})
..onError((x) {
toastBase.toastService.showToast(text: x.toString());
add(AuthEvent.logOut());
});
}
I think we cant use try-catch with the Streams,please inform me if I m wrong.
I am new to flutter. when I run my code , I got the error
E/flutter (16181): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Unhandled error type '() => Future<List<Food>>' is not a subtype of type 'List<Food>' occurred in Instance of 'MenuBloc'.
E/flutter (16181): #0 MenuBloc.mapEventToState (package:restuarant_app/Bloc/menue_bloc/menu_bloc.dart:30:7)
E/flutter (16181): <asynchronous suspension>
E/flutter (16181): #1 Bloc._bindEventsToStates.<anonymous closure> (package:bloc/src/bloc.dart:232:20)
E/flutter (16181): #2 Stream.asyncExpand.onListen.<anonymous closure> (dart:async/stream.dart:579:30)
E/flutter (16181): #3 _rootRunUnary (dart:async/zone.dart:1192:38)
E/flutter (16181): #4 _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter (16181): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7)
E/flutter (16181): #6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter (16181): #7 _DelayedData.perform (dart:async/stream_impl.dart:594:14)
E/flutter (16181): #8 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:710:11)
E/flutter (16181): #9 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:670:7)
E/flutter (16181): #10 _rootRun (dart:async/zone.dart:1180:38)
E/flutter (16181): #11 _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter (16181): #12 _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter (16181): #13 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
E/flutter (16181): #14 _rootRun (dart:async/zone.dart:1184:13)
E/flutter (16181): #15 _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter (16181): #16 _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter (16181): #17 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
E/flutter (16181): #18 _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
E/flutter (16181): #19 _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
E/flutter (16181):
E/flutter (16181): #0 Cubit.onError.<anonymous closure> (package:bloc/src/cubit.dart:140:7)
E/flutter (16181): #1 Cubit.onError (package:bloc/src/cubit.dart:141:6)
E/flutter (16181): #2 Bloc.onError (package:bloc/src/bloc.dart:113:11)
E/flutter (16181): #3 _rootRunBinary (dart:async/zone.dart:1204:38)
E/flutter (16181): #4 _CustomZone.runBinary (dart:async/zone.dart:1093:19)
E/flutter (16181): #5 _CustomZone.runBinaryGuarded (dart:async/zone.dart:995:7)
E/flutter (16181): #6 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:358:15)
E/flutter (16181): #7 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:376:16)
E/flutter (16181): #8 _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:275:7)
E/flutter (16181): #9 _SyncBroadcastStreamController._sendError.<anonymous closure> (dart:async/broadcast_stream_controller.dart:393:20)
E/flutter (16181): #10 _BroadcastStreamController._forEachListener (dart:async/broadcast_stream_controller.dart:327:15)
E/flutter (16181): #11 _SyncBroadcastStreamController._sendError (dart:async/broadcast_stream_controller.dart:392:5)
E/flutter (16181): #12 _BroadcastStreamController._addError (dart:async/broadcast_stream_controller.dart:294:5)
E/flutter (16181): #13 _rootRunBinary (dart:async/zone.dart:1204:38)
E/flutter (16181): #14 _CustomZone.runBinary (dart:async/zone.dart:1093:19)
E/flutter (16181): #15 _CustomZone.runBinaryGuarded (dart:async/zone.dart:995:7)
E/flutter (16181): #16 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:358:15)
E/flutter (16181): #17 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:376:16)
E/flutter (16181): #18 _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:275:7)
E/flutter (16181): #19 _ForwardingStreamSubscription._addError (dart:async/stream_pipe.dart:139:11)
E/flutter (16181): #20 _ForwardingStream._handleError (dart:async/stream_pipe.dart:104:10)
E/flutter (16181): #21 _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:170:13)
E/flutter (16181): #22 _rootRunBinary (dart:async/zone.dart:1204:38)
E/flutter (16181): #23 _CustomZone.runBinary (dart:async/zone.dart:1093:19)
E/flutter (16181): #24 _CustomZone.runBinaryGuarded (dart:async/zone.dart:995:7)
E/flutter (16181): #25 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:358:15)
E/flutter (16181): #26 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:376:16)
E/flutter (16181): #27 _DelayedError.perform (dart:async/stream_impl.dart:605:14)
E/flutter (16181): #28 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:710:11)
E/flutter (16181): #29 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:670:7)
E/flutter (16181): #30 _rootRun (dart:async/zone.dart:1180:38)
E/flutter (16181): #31 _C
I would like to get data from remote server.I use bloc library in my code.
This is part of menue_bloc.dart .I got error on line allFood= await _foodRepositiry.getAllFood() ;.
class MenuBloc extends Bloc<FoodEvent, MenuState> {
final _foodRepositiry = FoodRepository();
Map<String, List<Food>> mapFoodList;
MenuBloc({this.mapFoodList=const{}}) : super(InitialMenuState());
#override
// TODO: implement initialState
MenuState get initialState => InitialMenuState();
#override
Stream<MenuState> mapEventToState(FoodEvent event) async* {
print("loading....");
yield Loading();
if (event is GetAllFoodEvent) {
print("Get all food....");
this.mapFoodList = {};
List<Food> allFood;
allFood= await _foodRepositiry.getAllFood() ;
try {
print("in menu bloc...... ");
allFood.forEach((food) {
print(food.toString());
if (!this.mapFoodList.containsKey(food.category)) {
this.mapFoodList[food.category.toString()] = [];
}
this.mapFoodList[food.category].add(food);
});
yield Loaded(mapFoodList: this.mapFoodList);
} catch (e, stacktrace) {
print(e.toString());
print(stacktrace.toString());
When I change List<Food> allFood;to Future<List<Food>> allFood; it gives me following error
I/flutter (16181): type '() => Future<List<Food>>' is not a subtype of type 'Future<List<Food>>'
This FoodRepository code.
class FoodRepository{
final foodDao=new FoodDao();
final foodApiClient =new FoodApiClient();
Future getAllFood() async{
if(await checkInternetConnection()) {
print("fetch data from remote server");
return foodApiClient.fetchAllFood;
}else{
print("from db");
return foodDao.getAllFood();
}
}
}
This is FoodApiClient code:
class FoodApiClient{
static const baseUrl = '10.0.2.2';
final http.Client httpClient;
FoodApiClient({this.httpClient});
Future<List<Food>> fetchAllFood()async{
String url=":8080/resturant/food/allFood";
// print(url);
List<Food> foodList;
print(url);
final allFoodResponse=await httpClient.get(baseUrl+url);
print(allFoodResponse);
if (allFoodResponse.statusCode != 200) {
throw Exception('An error occured while loading food list!!! status code: '+allFoodResponse.statusCode.toString());
}
print("foodJson");
List foodJson = json.decode(allFoodResponse.body);
print(foodJson);
//foodJson.forEach((food) {foodList.add(Food.fromJson(food)); });
foodList=foodJson.map((f)=>Food.fromJson(f)).toList();
return foodList;
}
}
Future getAllFood() async{
needs to be
Future<List<Food>> getAllFood() async {
and then you need to follow the compiler errors from there, because there are a lot more instances that I cannot all name and describe here.
I strongly advise you to use proper dart formatting, and the package pedantic to tell you all about your code and how to improve it if you cannot find those places yourself.
While trying to show the notifications from flutter_local_notification it throws the following error:
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): Failed to handle method call
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:188)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:146)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:688)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:827)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:750)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:226)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:631)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at android.os.MessageQueue.next(MessageQueue.java:325)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at android.os.Looper.loop(Looper.java:142)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at android.app.ActivityThread.main(ActivityThread.java:6494)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
E/flutter (10962): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null)
E/flutter (10962): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (10962): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter (10962): <asynchronous suspension>
E/flutter (10962): #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
E/flutter (10962): #3 AndroidFlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/platform_flutter_local_notifications.dart:137:21)
E/flutter (10962): #4 FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:136:13)
E/flutter (10962): #5 NotificationPlugin.showNotification (package:pig_salang/models/notification_plugin.dart:94:43)
E/flutter (10962): #6 WelcomeScreen.build.<anonymous closure> (package:pig_salang/screens/welcome_screen.dart:42:36)
E/flutter (10962): #7 WelcomeScreen.build.<anonymous closure> (package:pig_salang/screens/welcome_screen.dart:41:26)
E/flutter (10962): #8 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:779:19)
E/flutter (10962): #9 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:862:36)
E/flutter (10962): #10 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (10962): #11 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:504:11)
E/flutter (10962): #12 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:282:5)
E/flutter (10962): #13 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:217:7)
E/flutter (10962): #14 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:475:9)
E/flutter (10962): #15 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (10962): #16 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:122:9)
E/flutter (10962): #17 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (10962): #18 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:120:18)
E/flutter (10962): #19 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:106:7)
E/flutter (10962): #20 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (10962): #21 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (10962): #22 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (10962): #23 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (10962): #24 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (10962): #25 _rootRunUnary (dart:async/zone.dart:1196:13)
E/flutter (10962): #26 _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter (10962): #27 _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7)
E/flutter (10962): #28 _invoke1 (dart:ui/hooks.dart:275:10)
E/flutter (10962): #29 _dispatchPointerDataPacket (dart:ui/hooks.dart:184:5)
E/flutter (10962):
As far as I have researched, the similar errors were shown because of the icon. I have added used every possible way to add icons, but it is not throwing the error constantly. Obviously, I rerun the app after each changes, to make sure I don't get the error.
My code looks like:
initializePlatformSpecifics() {
var initializeAndroidSettings = AndroidInitializationSettings('app_icon'); <--- Here
var initializeIOSSettings = IOSInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: true,
requestSoundPermission: true,
onDidReceiveLocalNotification: (id, title, body, payload) async {
ReceivedNotification receivedNotification = ReceivedNotification(
id: id, title: title, body: body, payload: payload);
didReceivedLocalNotificationSubject.add(receivedNotification);
},
);
initializeSettings = InitializationSettings(
initializeAndroidSettings, initializeIOSSettings);
}
I followed the tutorial. The thing is when I try to show the notification, it shows the above traceback.
I made notification icons in Android Studio -> app -> main -> res -> Image Asssets -> Notifications icon, then I made icon with name app_icon which I used to intialize the notification.
As it was not working, I also tried :
var initializeAndroidSettings = AndroidInitializationSettings('#mipmap/ic_launcher');
It also did not work. Any help would be appreciated!!!
'app_icon' was given for reference and it actually depends on where you image file is located, if you are using the default icon in mipmap folder named as ic_launcher for now then try the below code. Do let me know if it helps.
var initializeAndroidSettings
=AndroidInitializationSettings('mipmap/ic_launcher');
Here is my Client code and server is in c++. But when i am trying to connect this client to server it is throwing an error that websocket is not upgrading. The server is running i have checked with js client.
Code for client
import 'package:socketcluster_client/socketcluster_client.dart';
import 'dart:async';
class MyListener extends BasicListener {
#override
void onAuthentication(Socket socket, bool status) {
print('onAuthentication: socket $socket status $status');
}
#override
void onConnectError(Socket socket, e) {
print('onConnectError: socket $socket e $e');
}
#override
void onConnected(Socket socket) {
print('onConnected: socket $socket');
new Timer.periodic(const Duration(seconds: 2), (_) {
print('Attempting to send');
socket.emit('sampleClientEvent',
{'message': 'This is an object with a message property'});
});
}
#override
void onDisconnected(Socket socket) {
print('onDisconnected: socket $socket');
}
#override
void onSetAuthToken(String token, Socket socket) {
print('onSetAuthToken: socket $socket token $token');
socket.authToken = token;
}
}
main() async {
var socket = await Socket.connect('ws://10.5.11.88:7777/socketcluster/',
listener: new MyListener());
socket.on('rand', (name, data, ack) {
print('got message $data from event $name');
ack(name, 'No error', 'Hi there buddy');
});
}
I have tried https://github.com/flutter/flutter/issues/11444 but it is not working.
Error Log
Launching lib\main.dart on AOSP on IA Emulator in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...
Syncing files to device AOSP on IA Emulator...
E/flutter ( 5399): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled
Exception: WebSocketException: Connection to
'http://10.5.11.88:7777/socketcluster/#' was not upgraded to websocket
E/flutter ( 5399): #0 _WebSocketImpl.connect.<anonymous closure>.error
(dart:_http/websocket_impl.dart:1054:9)
E/flutter ( 5399): #1 _WebSocketImpl.connect.<anonymous closure>
(dart:_http/websocket_impl.dart:1063:14)
E/flutter ( 5399): #2 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter ( 5399): #3 _CustomZone.runUnary
(dart:async/zone.dart:1031:19)
E/flutter ( 5399): #4 _FutureListener.handleValue
(dart:async/future_impl.dart:139:18)
E/flutter ( 5399): #5 Future._propagateToListeners.handleValueCallback
(dart:async/future_impl.dart:680:45)
E/flutter ( 5399): #6 Future._propagateToListeners
(dart:async/future_impl.dart:709:32)
E/flutter ( 5399): #7 Future._completeWithValue
(dart:async/future_impl.dart:524:5)
E/flutter ( 5399): #8 Future.wait.<anonymous closure>
(dart:async/future.dart:400:22)
E/flutter ( 5399): #9 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter ( 5399): #10 _CustomZone.runUnary
(dart:async/zone.dart:1031:19)
E/flutter ( 5399): #11 _FutureListener.handleValue
(dart:async/future_impl.dart:139:18)
E/flutter ( 5399): #12 Future._propagateToListeners.handleValueCallback
(dart:async/future_impl.dart:680:45)
E/flutter ( 5399): #13 Future._propagateToListeners
(dart:async/future_impl.dart:709:32)
E/flutter ( 5399): #14 Future._completeWithValue
(dart:async/future_impl.dart:524:5)
E/flutter ( 5399): #15 Future._asyncComplete.<anonymous closure>
(dart:async/future_impl.dart:554:7)
E/flutter ( 5399): #16 _rootRun (dart:async/zone.dart:1126:13)
E/flutter ( 5399): #17 _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter ( 5399): #18 _CustomZone.runGuarded
(dart:async/zone.dart:925:7)
E/flutter ( 5399): #19 _CustomZone.bindCallbackGuarded.<anonymous
closure> (dart:async/zone.dart:965:23)
E/flutter ( 5399): #20 _microtaskLoop
(dart:async/schedule_microtask.dart:43:21)
E/flutter ( 5399): #21 _startMicrotaskLoop
(dart:async/schedule_microtask.dart:52:5)
E/flutter ( 5399):
Actually strict application load balancer policy was applied on AWS/server
Relaxing it solved the issue