'Flutter: How to get asset path (video) for File class

I saved a video in my asset folder and i am trying to get the video using the File class.

For example:

Final File video = File(String path);

So my question is where can i find the String path?

I already added this file to the pubspec.yaml

assets:
    - assets/mbf.mp4

Thank you

Answer

getVideo() async {
var response = await rootBundle.load('assets/mbf.mp4');
final directory = await getApplicationDocumentsDirectory();
var file = File("${directory.path}/mbf.mp4"); 
file.writeAsBytesSync(response.buffer.asUint8List());

//Use it with VideoPlayer

controller = VideoPlayerController.file(file)
  ..addListener(() => setState(() {}))
  ..setLooping(true)
  ..initialize().then((_) => controller.play());
 }


Solution 1:[1]

You need copy file to device and then get path of file.

See exampl code:

void _copyAssetToLocal() async {
try {
  var content = await rootBundle.load("assets/intro.mp4");
  final directory = await getApplicationDocumentsDirectory();
  var file = File("${directory.path}/intro.mp4");
  file.writeAsBytesSync(content.buffer.asUint8List());
  loadIntroVideoMethod(file.path);
} catch (e) {
  
}}

Solution 2:[2]

The path is assets/mbf.mp4, but it is not compatible with File constructor.

See Adding assets and images for details.

Using AssetBundle data can be loaded, which of course can be written to a file.

import 'package:flutter/services.dart' show rootBundle;

final byteData = await rootBundle.load('assets/mbf.mp4');

Play video directly from assets use VideoPlayerController.asset constructor.

    _controller = VideoPlayerController.asset('assets/mbf.mp4')
      ..initialize().then((_) {
        // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
        setState(() {});
      });

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 Esmaeil Ahmadipour
Solution 2