Dart return Future<dynamic> previously casted as different Type from a function

Viewed 40

I need to return some type as Future<dynamic>. I have attached a simplified version of my code. I always get the Error "A value of type 'String' can't be returned from function 'testFunc' because it has a return type of 'Future'"

Even if i do "dynamic returnVal = text" and return that, i got an exception "Unhandled exception: type 'String' is not a subtype of type 'Future< dynamic>'"

import 'dart:async';

void main(List<String> args) async {
  dynamic gotVal = await testFunc();

  print(gotVal);
}

Future<dynamic> testFunc() {
  String text = "Bla";
  return text;
}

I was able to fix it with a Completer, but for me that seems wrong. Is it really the only solution to use a Completer like this? :

import 'dart:async';

void main(List<String> args) async {
  dynamic gotVal = await testFunc();

  print(gotVal);
}

Future<dynamic> testFunc() {
  String text = "Bla";

  Completer completer = Completer();
  completer.complete(text);

  return completer.future;
}
1 Answers

You should rewrite your testFunc adding async keyword to its definition:

Future<dynamic> testFunc() async {
  String text = "Bla";
  return text;
}
Related