'Flutter - how do I get the duration of a picked video file on Web?

I've tried everything and failed to determine the duration of a picked video file on Flutter Web. All libraries on pub.dev need a 'File' and this is not available on the web.

I've not been able to get this from the metadata either.



Solution 1:[1]

What worked for me, though I am unhappy with the solution approach is:

Widget buildHiddenVideoPlayer(Key key) {
    var _videoElement = html.VideoElement();
    _videoElement.id = 'htmlHiddenVideoID';
    _videoElement.autoplay = true;
    _videoElement.muted = true;
    _videoElement.loop = true;
    _videoElement.controls = false;
    _videoElement.defaultMuted = true;
    if (fileData != null) {
      _videoElement.src = xfile.path; // where xfile is the file picked as XFile
    }

    // ignore: undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(
      'htmlHiddenVideoID',
      (int viewId) => _videoElement,
    );
    return HtmlElementView(
      key: key,
      viewType: 'htmlHiddenVideoID',
    );
  }

This widget is hidden in a 5 x 5 sized box behind a iFrame widget (in my implementation)

Then when I need the duration of a picked file:

VideoElement element = document.getElementById('htmlHiddenVideoID') as VideoElement;
      setState(() {
        element.src = pickedFile.path;
      });
      while (true) {
        await Future.delayed(const Duration(milliseconds: 200), () {});
        duration = element.duration;
        if (!duration.isNaN) break; // duration is not returned immediately in many cases
      }
      element.pause(); // stops the hidden video from playing and consuming resources

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sunil Gupta