Samuella M. Aglago
Samuella M. Aglago

Reputation: 105

Returning a string from a Future's callback function

I think this should be easy but I am pretty confused. I want to return 'result' from the callback function of Future.delay and I don't know why it is throwing an error of 'The non-nullable local variable 'result' must be assigned before it can be used' meanwhile there is no error on the course material I am using. below is the code.

String task2(){

Duration three = Duration(seconds: 3);
String result;

Future.delayed(three, (){
result = 'task 2 data';
print('task 2 complete');
});

return result;

}

"result" in "return result" is the error here.

Upvotes: 1

Views: 585

Answers (1)

TmKVU
TmKVU

Reputation: 3000

You simply can't return a String from a function where the content of that String comes from a Future. What you could do is the following:

void main() async {
  final result = await task2();
  print(result);
}

Future<String> task2() {
  Duration three = Duration(seconds: 3);
  return Future.delayed(three, () {
    print('task 2 complete');
    return 'task 2 data';
  });
}

Upvotes: 2

Related Questions