Search code examples
dartasync-awaittypeerror

Dart: The argument type 'String' can't be assigned to the parameter type 'FutureOr<String>


I'm experimenting a bit with async methods but I'm having a hard time.

I would like to implement some code whose goal is to simply return a string after waiting 2 seconds.

This is my first attempt and related error

String setUserDecision() {
    return 'Yes'; 
}

Future<String> fetchUserDecision() async {
  return await Future.delayed(const Duration(seconds: 2), setUserDecision());
}

Future<void> main() async {
  print("Fetching user role...");
  String decision = await fetchUserDecision();
  print('The user decision is: $decision');
  print("Done");
}
Error: The argument type 'String' can't be assigned to the parameter type 'FutureOr<String> Function()?'.
  return await Future.delayed(const Duration(seconds: 2), setUserDecision());

I can't understand the error, I may think the String type is not right, but I don't understand how to change it. I also tried this solution, thinking it might make sense (maybe), but nothing.

Future<String> setUserDecision() async{
    return await 'Yes'; 
}

Future<String> fetchUserDecision() async {
  return await Future.delayed(const Duration(seconds: 2), setUserDecision());
}

Future<void> main() async {
  print("Fetching user role...");
  String decision = await fetchUserDecision();
  print('The user decision is: $decision');
  print("Done");
}

and also this

import 'dart:async';

String setUserDecision() {
    return  'Yes'; 
}

Future<String> fetchUserDecision() async {
  return await Future.delayed(const Duration(seconds: 2), setUserDecision() as FutureOr<String> Function()?);
}

Future<void> main() async {
  print("Fetching user role...");
  String decision = await fetchUserDecision();
  print('The user decision is: $decision');
  print("Done");
}

with this error

_CastError (type 'String' is not a subtype of type '(() => FutureOr<String>)?' in type cast)

The only solution that seems to work is this

Future<String> fetchUserDecision() async {
  return await Future.delayed(const Duration(seconds: 2), () {
    return 'Yes'; 
});
}

Future<void> main() async {
  print("Fetching user role...");
  String decision = await fetchUserDecision();
  print('The user decision is: $decision');
  print("Done");
}

but I would like to better understand the type of error and how to fix it.


Solution

  • Your problem is that you are calling your setUserDecision() function and takes the result of this and sends to Future.delayed which expect a function. Since the result of calling setUserDecision() is a String, you end up providing a String instead of a Function which makes Dart complain.

    You should do this instead:

    Future<String> fetchUserDecision() async {
      return await Future.delayed(const Duration(seconds: 2), setUserDecision);
    }
    

    Notice I have removed the () after setUserDecision. Now we provide the function as a function instead of calling it.