在初始化视频控制器之前设置视频路径 [英] Setting video path before initializing video controller

查看:111
本文介绍了在初始化视频控制器之前设置视频路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试使用flutter的示例来测试视频,但我想提供一个保存在永久性存储中的文件路径。我的问题是我无法解决该问题。

So, I'm trying to use flutter's example to test a video, but I want to provide a file path that is saved in the persistent storage. My problem is that I can't wrap my head around on how to do that.

这是我的代码: https://dartpad.dev/6930fc8c208c9bd1c00ae34303365e48

Future<String> getVideo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var videoid = prefs.getString('fileview');
    return videoid;
  }

  @override
  void initState() {
    getVideo();

    _controller = VideoPlayerController.file(File(getVideo()));
    // Initialize the controller and store the Future for later use.
    _initializeVideoPlayerFuture = _controller.initialize();

    // Use the controller to loop the video.
    _controller.setLooping(true);

    super.initState();
  }
  }

所以我无法将getVideo()设置为File因为这是initstate的未来。

So I can't set getVideo() to File because it's a future in initstate.

推荐答案

您可以编写另一个异步函数来初始化控制器,并聆听该未来以构建UI

You can write another async function for initialising your controller and listen that future for building your UI.

Future initPlayer() async {
   var filePath = await getVideo();
   _controller = VideoPlayerController.file(File(filePath));
   _initializeVideoPlayerFuture = _controller.initialize();
   _controller.setLooping(true);
   return _initializeVideoPlayerFuture;
}

您必须编写另一个函数来处理游戏状态,因为玩家会

You have to write another function to handle the playing state, because the player will be null when the build method will run for the first time.

bool get isVideoPlaying {
   return _controller?.value?.isPlaying != null && _controller.value.isPlaying;
}

最后,修改构建方法,例如:

Finally, modify your build method like:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Butterfly Video'),
    ),
    body: FutureBuilder(
      future: initPlayer(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return AspectRatio(
            aspectRatio: _controller.value.aspectRatio,
            child: VideoPlayer(_controller),
          );
        } else {
          return Center(child: CircularProgressIndicator());
        }
      },
    ),
    floatingActionButton: FloatingActionButton(
      onPressed: () {
        setState(() {
          if (isVideoPlaying) {
            _controller?.pause();
          } else {
            _controller?.play();
          }
        });
      },
      child: Icon(
        isVideoPlaying ? Icons.pause : Icons.play_arrow,
      ),
    ),
  );
}

这篇关于在初始化视频控制器之前设置视频路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆