【问题标题】:Setting video path before initializing video controller在初始化视频控制器之前设置视频路径
【发布时间】:2020-07-18 04:41:50
【问题描述】:

所以,我正在尝试使用颤振的示例来测试视频,但我想提供一个保存在持久存储中的文件路径。我的问题是我不知道该怎么做。

这是我的代码: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 中的未来。

【问题讨论】:

    标签: flutter asynchronous video dart


    【解决方案1】:

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

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

    您必须编写另一个函数来处理播放状态,因为第一次运行构建方法时播放器将为空。

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

    最后,修改你的构建方法:

    @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,
          ),
        ),
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-14
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      相关资源
      最近更新 更多