Reputation: 1304
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...???
Upvotes: 0
Views: 805
Reputation: 4576
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.
Upvotes: 1
Reputation: 17940
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
}
Upvotes: 1
Reputation: 63709
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);
}
Upvotes: 1