Search code examples
jsonflutterdartflutter-futurebuilder

Flutter Casting a Map<String, dynamic> to Future<Map<String, dynamic>> forcefully returns Error


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...???


Solution

  • 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
    }