Error: Unable to handle function call in Cloud Functions Firestore - flutter

I want to receive the document form current user uid passed at client side. I tried it using functions.onRequest and successfully got the result but I got the error that while using onCall method.
Cloud Function
exports.getUserData = functions.https.onCall((data) => {
const test = data.text;
db.collection('users').doc(test).get().then((value)=>{
return value.data();
}).catch((e)=>{
return ("Error in CFunction"+e);
})
});
Client-side Call
Future _callable()async{
FirebaseUser currentUser = await _auth.currentUser();
final uid = currentUser.uid;
final HttpsCallable callable =
CloudFunctions.instance.getHttpsCallable(functionName: 'getUserData');
var data = await callable.call(uid);
print(data.data);
}
Error I am getting
E/MethodChannel#cloud_functions(12458): Failed to handle method call
E/MethodChannel#cloud_functions(12458): java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map
E/MethodChannel#cloud_functions(12458): at io.flutter.plugins.firebase.cloudfunctions.CloudFunctionsPlugin.onMethodCall(CloudFunctionsPlugin.java:37)
E/MethodChannel#cloud_functions(12458): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:226)
E/MethodChannel#cloud_functions(12458): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#cloud_functions(12458): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:631)
E/MethodChannel#cloud_functions(12458): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#cloud_functions(12458): at android.os.MessageQueue.next(MessageQueue.java:334)
E/MethodChannel#cloud_functions(12458): at android.os.Looper.loop(Looper.java:174)
E/MethodChannel#cloud_functions(12458): at android.app.ActivityThread.main(ActivityThread.java:6939)
E/MethodChannel#cloud_functions(12458): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#cloud_functions(12458): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/MethodChannel#cloud_functions(12458): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:870)
E/flutter (12458): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Exception: Unable to call function getUserData
E/flutter (12458): #0 HttpsCallable.call (package:cloud_functions/src/https_callable.dart:50:9)
E/flutter (12458): <asynchronous suspension>
E/flutter (12458): #1 _HomePageState._callable (package:firebaselogin/homepage.dart:160:35)
E/flutter (12458): <asynchronous suspension>
E/flutter (12458): #2 _HomePageState.build.<anonymous closure> (package:firebaselogin/homepage.dart:97:23)
E/flutter (12458): #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:779:19)
E/flutter (12458): #4 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:862:36)
E/flutter (12458): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (12458): #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:504:11)
E/flutter (12458): #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:282:5)
E/flutter (12458): #8 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:217:7)
E/flutter (12458): #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:475:9)
E/flutter (12458): #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (12458): #11 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:122:9)
E/flutter (12458): #12 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (12458): #13 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:120:18)
E/flutter (12458): #14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:106:7)
E/flutter (12458): #15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (12458): #16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (12458): #17 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (12458): #18 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (12458): #19 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (12458): #20 _rootRunUnary (dart:async/zone.dart:1196:13)
E/flutter (12458): #21 _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter (12458): #22 _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7)
E/flutter (12458): #23 _invoke1 (dart:ui/hooks.dart:275:10)
E/flutter (12458): #24 _dispatchPointerDataPacket (dart:ui/hooks.dart:184:5)

Callable functions must return a promise that resolves with the data to send to the client. Right now, your function actually isn't returning anything at all. You should probably return the promise returned by get().
exports.getUserData = functions.https.onCall((data) => {
const test = data.text;
return db.collection('users').doc(test).get();
});

Related

flutter showing Unhandled Exception: FormatException: Filter error, bad data error

when I am trying to make an HTTP request in flutter I am receiving these errors on a particular API and I am unable to figure out what it means and how to resolve this error is it API is working properly in postman and browser
> E/flutter (15337): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FormatException: Filter error, bad data
E/flutter (15337): #0 _FilterImpl.processed (dart:io-patch/filter_patch.dart:11:32)
E/flutter (15337): #1 _FilterSink.addSlice (dart:io/data_transformer.dart:537:29)
E/flutter (15337): #2 _FilterSink.add (dart:io/data_transformer.dart:521:5)
E/flutter (15337): #3 _ConverterStreamEventSink.add (dart:convert/chunked_conversion.dart:72:18)
E/flutter (15337): #4 _SinkTransformerStreamSubscription._handleData (dart:async/stream_transformers.dart:111:24)
E/flutter (15337): #5 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (15337): #6 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (15337): #7 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (15337): #8 CastStreamSubscription._onData (dart:_internal/async_cast.dart:85:11)
E/flutter (15337): #9 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (15337): #10 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (15337): #11 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (15337): #12 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter (15337): #13 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (15337): #14 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)
E/flutter (15337): #15 _HandleErrorStream._handleData (dart:async/stream_pipe.dart:256:10)
E/flutter (15337): #16 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (15337): #17 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (15337): #18 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (15337): #19 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (15337): #20 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter (15337): #21 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
E/flutter (15337): #22 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:706:11)
E/flutter (15337): #23 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:663:7)
E/flutter (15337): #24 _rootRun (dart:async/zone.dart:1346:47)
E/flutter (15337): #25 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (15337): #26 _CustomZone.runGuarded (dart:async/zone.dart:1162:7)
E/flutter (15337): #27 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1202:23)
E/flutter (15337): #28 _rootRun (dart:async/zone.dart:1354:13)
E/flutter (15337): #29 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (15337): #30 _CustomZone.runGuarded (dart:async/zone.dart:1162:7)
E/flutter (15337): #31 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1202:23)
E/flutter (15337): #32 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter (15337): #33 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter (15337):
I have tried adding other API which is am using in my application and code is working properly but for it is giving above exception and stops after HTTP call.
Future<Null> getNewHomeData() async {
setState(() {
loading = true;
});
final response = await http.get(Uri.parse(Uri.encodeFull(APIs.url_HomePage)));
print(response.statusCode);
print(response.body);
try {
print(response.body);
if(response.statusCode == 200){
final home = homeNewFromJson(response.body);
homeBanner = home.advImg;
homeContent = home.infoText;
shopCat = home.shopCat;
storeImg = home.storeImg;
topSellings = home.topSellings;
modularFurniture = home.modularFurniture;
decorFurniture = home.decorFurniture;
banner1 = home.banner1;
banner2 = home.banner2;
banner3 = home.banner3;
banner4 = home.banner4;
banner5 = home.banner5;
}
} on Exception catch (e) {
print(e);
}

Flutter Unable catch Exception using tryCatch

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.

type '() => Future<List<Food>>' is not a subtype of type <List<Food>

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.

Why will it not let me take a picture using the Camera Controller?

I am trying to create an application using a full-screen camera. The live camera feed works as well as button feedback. It seems that there is a problem at the _controller.takePicture(path) line as the "IS INITIALIZED" print statement returns true. I put the path, path provider, and camera dependencies in pubspec.yaml.
Initialization of CameraController
cameras = await availableCameras();
var frontCamera = cameras.first;
_controller = CameraController(frontCamera, ResolutionPreset.high);
try {
await _controller.initialize();
} catch (e) {
}
print('Controller Is Init:' + _controller.value.isInitialized.toString());
displayPreview();
child: GestureDetector(
behavior: HitTestBehavior.translucent,
child:Container(
child: Icon(Icons.camera,color: Colors.white,size: 60,)),
onTap: () async {
print('IS INITIALIZED'+_controller.value.isInitialized.toString());
try {
await _controller.takePicture(path);
}
catch(e){
print('E:'+e);
}
Error:
E/MethodChannel#plugins.flutter.io/camera(28109): Failed to handle method call
E/MethodChannel#plugins.flutter.io/camera(28109): java.lang.NullPointerException
E/MethodChannel#plugins.flutter.io/camera(28109): at java.io.File.<init>(File.java:283)
E/MethodChannel#plugins.flutter.io/camera(28109): at io.flutter.plugins.camera.Camera.takePicture(Camera.java:227)
E/MethodChannel#plugins.flutter.io/camera(28109): at io.flutter.plugins.camera.MethodCallHandlerImpl.onMethodCall(MethodCallHandlerImpl.java:77)
E/MethodChannel#plugins.flutter.io/camera(28109): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:230)
E/MethodChannel#plugins.flutter.io/camera(28109): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#plugins.flutter.io/camera(28109): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:664)
E/MethodChannel#plugins.flutter.io/camera(28109): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#plugins.flutter.io/camera(28109): at android.os.MessageQueue.next(MessageQueue.java:336)
E/MethodChannel#plugins.flutter.io/camera(28109): at android.os.Looper.loop(Looper.java:197)
E/MethodChannel#plugins.flutter.io/camera(28109): at android.app.ActivityThread.main(ActivityThread.java:8125)
E/MethodChannel#plugins.flutter.io/camera(28109): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#plugins.flutter.io/camera(28109): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
E/MethodChannel#plugins.flutter.io/camera(28109): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
E/flutter (28109): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: type 'CameraException' is not a subtype of type 'String'
E/flutter (28109): #0 _VisualPageState.build.<anonymous closure> (package:ourearth2020/screens/VisualPage.dart:209:36)
E/flutter (28109): <asynchronous suspension>
E/flutter (28109): #1 _VisualPageState.build.<anonymous closure> (package:ourearth2020/screens/VisualPage.dart)
E/flutter (28109): #2 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter (28109): #3 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter (28109): #4 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter (28109): #5 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
E/flutter (28109): #6 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
E/flutter (28109): #7 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
E/flutter (28109): #8 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
E/flutter (28109): #9 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter (28109): #10 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
E/flutter (28109): #11 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
E/flutter (28109): #12 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
E/flutter (28109): #13 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter (28109): #14 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter (28109): #15 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter (28109): #16 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter (28109): #17 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter (28109): #18 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter (28109): #19 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter (28109): #20 _invoke1 (dart:ui/hooks.dart:283:10)
E/flutter (28109): #21 _dispatchPointerDataPacket (dart:ui/hooks.dart:192:5)
This looks like the path you provide as a parameter is not a String but a CameraException.
To create a path, you can do that (requires path_provider) :
final path = (await getTemporaryDirectory()).path + '${DateTime.now()}.png';

Flutter local notifications throwing an error

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');