I have a function that contains some Future returns as show below.
Future<Map<String, dynamic>> myFunction() {
if(some_condition){
returnFromThisFunc = {
'status': false,
'message':'Some message',
'data': {}
} as Future<Map<String, dynamic>>; // Error mentioning this line at 'as'
} else {
// Returning "Future<Map<String, dynamic>> returnFromThisFunc" return from some API and etc functions that are working fine.
}
return returnFromThisFunc;
}
Now the problem is that if my some_condition
is false then it is working fine and function is returning the data but when some_condition
is true then it is giving me this error Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Future<Map<String, dynamic>>' in type cast
How to fix this and return Future<Map<String, dynamic>>
in any way...???
CodePudding user response:
You can use Future.value
on return.
Future<Map<String, dynamic>> myFunction() {
Map<String, dynamic> returnFromThisFunc;
if (1 < 2) {
returnFromThisFunc = {
'status': false,
'message': 'Some message',
'data': {}
};
} else {
returnFromThisFunc = {};
}
return Future.value(returnFromThisFunc);
}
CodePudding user response:
When your function return type is Future
you should use await in it, but when you don't have any async method in it, you should use Future.value
for returning value. try this:
Future<Map<String, dynamic>> myFunction() {
if(some_condition){
returnFromThisFunc = {
'status': false,
'message':'Some message',
'data': {}
}
} else {
// Returning "Future<Map<String, dynamic>> returnFromThisFunc" return from some API and etc functions that are working fine.
}
return Future.value(returnFromThisFunc) ;/// <--- add this
}
CodePudding user response:
Try the following code:
Future<Map<String, dynamic>> myFunction() {
if(some_condition){
returnFromThisFunc = {
'status': false,
'message':'Some message',
'data': {}
}
} else {
// Returning "Future<Map<String, dynamic>> returnFromThisFunc" return from some API and etc functions that are working fine.
}
return Future.value(returnFromThisFunc); // <= add this
}
Feel free to comment me if you have any questions.