Home > Blockchain >  How to get the return value of future
How to get the return value of future

Time:07-27

Implementation is like this below.

Future<Duration?> getCurrentPosition() async {
  final milliseconds = await _platform.getCurrentPosition(playerId);
  if (milliseconds == null) {
    return null;
  }
  return Duration(milliseconds: milliseconds);
}

I want to get the Duration(milliseconds: milliseconds);

So I wrote this code.

Duration t = await widget.audioPlayerHandler.audioPlayer.getCurrentPosition();

My code is above.

But this shows error below, somehow it returns int??

How can I get the Duration that function returns?

lib/main.dart:468:18: Error: A value of type 'int' can't be assigned to a variable of type 'Duration'.
 - 'Duration' is from 'dart:core'.
    Duration t = await widget.audioPlayerHandler.audioPlayer.getCurrentPosition();

CodePudding user response:

There are two things here This method returns nullable data and milliseconds can only take int.

Future<Duration?> getCurrentPosition() async {
  final milliseconds = await _platform.getCurrentPosition(playerId);
  if (milliseconds == null) {
    return null;
  }
  return Duration(milliseconds:int.tryParse(milliseconds)??0);
}

and get nullable duration like Duration? t or provide default value.

Duration  t = await widget.audioPlayerHandler.audioPlayer.getCurrentPosition()??Duration.zero;
  • Related