Flutter Chewie和视频播放器问题,即使在处理控制器后,视频仍然在后台播放,也尝试暂停视频

11dmarpk  于 2023-08-07  发布在  Flutter
关注(0)|答案(1)|浏览(200)

这里是我的Flutter应用程序的代码,我面临着一个主要问题,即使关闭包含视频播放器的小部件后,确保处理被调用,视频仍然保持在后台播放不知道这个问题是与chewie控制器或视频播放器。
甚至尝试暂停视频处理,但没有工作,我甚至不认为暂停是正确的选择,因为我使用这个小部件多次,它会增加负载。
有谁能帮我这个忙吗???

class VideoPlayerApp extends StatefulWidget {
  final String jsonLink;
  final String fileTitle;
  final String userId;
  final String creationTime;
  final bool showOnlyfile;

  const VideoPlayerApp(this.jsonLink, this.fileTitle, this.userId, this.creationTime, this.showOnlyfile, {super.key});
  @override
  State<VideoPlayerApp> createState() => _VideoPlayerAppState();
}

class _VideoPlayerAppState extends State<VideoPlayerApp>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  String videoRootUrl = "";
  late VideoPlayerController videoPlayerController;
  late  ChewieController chewieController;
  // late VideoPlayerController videoPlayerController;

  Future<String> fetchJsonContent() async {
    final jsonResponse = await http.get(Uri.parse(widget.jsonLink));
    if (jsonResponse.statusCode == 200) {
      var jsonContent = jsonDecode(jsonResponse.body);
      videoRootUrl = jsonContent["meta"]["rootUrl"];
      var files = jsonContent["files"];
      if (files.length > 0) {
        return videoRootUrl + files[0];
      }
      return "";
    } else {
      throw Exception('Failed to load json file of drive');
    }
  }

  @override
  void dispose() {
    print("|||||||||Video Dispose Called|||||||");
    videoPlayerController.dispose();
    chewieController.dispose();
    chewieController.videoPlayerController.pause();
    chewieController.pause();
    videoPlayerController.pause();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return WillPopScope(
      onWillPop: ()async{
        switch(contentUiPreviousPath){
          case "contentList":
            Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=>courseContent(creatorName: currentCourseCreator, courseId: currentCourseId, batchId: currentBatchId, batchTitle: currentBatchTitle, discussionChannel: discussionChannel, announcementChannnel: announcementChannnel, tabBarIndex: 1)));
            break;
          default:
            Navigator.of(context).pop();
            break;
        }
        return false;
      },
      child: Scaffold(
          appBar: (widget.showOnlyfile)?null:const CustomAppBar(networkId: 'No-Network',tempNetworkImgUrl: ""),
          drawer: (widget.showOnlyfile)?null:const CustomDrawer(),
          body: bindVideoFiles()),
    );
  }

  bindVideoFiles() {
    return FutureBuilder(
      future: fetchJsonContent(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasData) {
          videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(snapshot.data));

          chewieController = ChewieController(
            videoPlayerController: videoPlayerController,
            autoPlay: false,
            autoInitialize: true,
            looping: false,
            showControls: true,
            aspectRatio: 16 / 9,
            materialProgressColors: ChewieProgressColors(
              backgroundColor: const Color.fromARGB(255, 4, 50, 90),
              bufferedColor: const Color.fromARGB(255, 4, 66, 116),
            ),
            errorBuilder: (context, errorMessage) {
              print("Video Player error --- $errorMessage");
              return const Center(
                child: Icon(Icons.error,color: Colors.white,),
              );
            },
          );

          return SingleChildScrollView(
            child: Column(
              children: [
                (widget.showOnlyfile)?const SizedBox():Container(
                        padding: const EdgeInsets.symmetric(
                          vertical: 13,
                        ),
                        width: MediaQuery.of(context).size.width * .9,
                        alignment: Alignment.centerLeft,
                        decoration: const BoxDecoration(
                            border: Border(
                                bottom: BorderSide(
                          width: 2,
                          color: Colors.black54,
                        ))),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              widget.fileTitle,
                              style: const TextStyle(
                                fontSize: 20,
                                fontWeight: FontWeight.bold,
                                color: Colors.black45,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                            const SizedBox(
                              height: 3,
                            ),
                            Text(
                              widget.creationTime,
                              style: const TextStyle(
                                fontSize: 12,
                                color: Colors.black45,
                              ),
                              maxLines: 1,
                              textAlign: TextAlign.left,
                              overflow: TextOverflow.ellipsis,
                            ),
                            const SizedBox(
                              height: 3,
                            ),
                          ],
                        ),
                      ),
                Container(
                    height: (MediaQuery.of(context).size.width * 9) / 16,
                    margin: const EdgeInsets.symmetric(vertical: 20),
                    decoration: const BoxDecoration(color: Colors.black),
                    child: Chewie(
                      controller: chewieController,
                    )),
              ],
            ),
          );
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }
}

字符串
我尝试处理和暂停视频,但没有工作。

9nvpjoqh

9nvpjoqh1#

嗯,我改变了一些事情,现在我可以暂停播放器和处置它-以下是我改变的事情-删除wantkeepAlive,删除未来的建设者,改变处置一点,并没有直接创建任何视频播放器控制器。
这是我的代码,如果有人需要它在未来

class VideoPlayerApp extends StatefulWidget {
  final String jsonLink;
  final String fileTitle;
  final String userId;
  final String creationTime;
  final bool showOnlyfile;

  const VideoPlayerApp(this.jsonLink, this.fileTitle, this.userId, this.creationTime, this.showOnlyfile, {super.key});
  @override
  State<VideoPlayerApp> createState() => _VideoPlayerAppState();
}

class _VideoPlayerAppState extends State<VideoPlayerApp> {

  bool keepLoading = true;
  String videoRootUrl = "";
  late  ChewieController chewieController;

  Future<String> fetchJsonContent() async {
    final jsonResponse = await http.get(Uri.parse(widget.jsonLink));
    if (jsonResponse.statusCode == 200) {
      var jsonContent = jsonDecode(jsonResponse.body);
      videoRootUrl = jsonContent["meta"]["rootUrl"];
      var files = jsonContent["files"];
      if (files.length > 0) {
        return videoRootUrl + files[0];
      }
      return "";
    } else {
      throw Exception('Failed to load json file of drive');
    }
  }

  @override
  void dispose() {
    print("|||||||||Video Dispose Called|||||||");
    chewieController.videoPlayerController.pause();
    chewieController.dispose();
    super.dispose();
  }

  void initState(){
    super.initState();
    initailSetup();
  }

  void initailSetup()async{
    String tempUrl = await fetchJsonContent();
    chewieController = ChewieController(
      videoPlayerController: VideoPlayerController.networkUrl(Uri.parse(tempUrl),videoPlayerOptions: VideoPlayerOptions(allowBackgroundPlayback: false),),
      autoPlay: false,
      autoInitialize: true,
      looping: false,
      showControls: true,
      aspectRatio: 16 / 9,
      materialProgressColors: ChewieProgressColors(
        backgroundColor: const Color.fromARGB(255, 4, 50, 90),
        bufferedColor: const Color.fromARGB(255, 4, 66, 116),
      ),
      errorBuilder: (context, errorMessage) {
        print("Video Player error --- $errorMessage");
        return const Center(
          child: Icon(Icons.error,color: Colors.white,),
        );
      },
    );
    print("Chewie controller set ----");
    setState(() {
      keepLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: ()async{
        switch(contentUiPreviousPath){
          case "contentList":
            Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=>courseContent(creatorName: currentCourseCreator, courseId: currentCourseId, batchId: currentBatchId, batchTitle: currentBatchTitle, discussionChannel: discussionChannel, announcementChannnel: announcementChannnel, tabBarIndex: 1)));
            break;
          default:
            Navigator.of(context).pop();
            break;
        }
        return false;
      },
      child: Scaffold(
          appBar: (widget.showOnlyfile)?null:CustomAppBar(networkId: 'No-Network',tempNetworkImgUrl: ""),
          drawer: (widget.showOnlyfile)?null:const CustomDrawer(),
          body: (keepLoading)?const Center(child: CircularProgressIndicator(),)
          :Column(
            children: [
              (widget.showOnlyfile)?const SizedBox():Container(
                padding: const EdgeInsets.symmetric(
                  vertical: 13,
                ),
                width: MediaQuery.of(context).size.width * .9,
                alignment: Alignment.centerLeft,
                decoration: const BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                          width: 2,
                          color: Colors.black54,
                        ))),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      widget.fileTitle,
                      style: const TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Colors.black45,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 3,),
                    Text(
                      widget.creationTime,
                      style: const TextStyle(
                        fontSize: 12,
                        color: Colors.black45,
                      ),
                      maxLines: 1,
                      textAlign: TextAlign.left,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 3,),
                  ],
                ),
              ),
              Container(
                  height: (MediaQuery.of(context).size.width * 9) / 16,
                  margin: const EdgeInsets.symmetric(vertical: 20),
                  decoration: const BoxDecoration(color: Colors.black),
                  child: Chewie(
                    controller: chewieController,
                  )),
            ],
          )),
    );
  }
}

字符串

相关问题