You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Flutter中使用chewie:^0.9.10实现切至其他APP时停视频后台播放

Solution for Controlling Chewie Video Playback on App Lifecycle Changes

Core Idea

Let's break this down simply: since Chewie is built on top of the video_player package, we can use Flutter's built-in app lifecycle listener to pause the video when the app gets sent to the background (like when the user opens another app) and resume it when the app comes back to the foreground. For all other scenarios—like navigating between screens within your app—the video will keep playing as you need.

Step-by-Step Implementation

  1. Double-Check Dependencies
    You already have chewie: ^0.9.10 in your pubspec.yaml, just make sure video_player is included too (it's a required dependency for Chewie, so the pub resolver will pull a compatible version automatically, but you can add it explicitly if you want).

  2. Add Lifecycle Listening to Your Video Page
    We'll create a StatefulWidget that mixes in WidgetsBindingObserver—this lets us listen to when the app's state changes. Then we'll override the lifecycle method to control playback.

Here's a complete, working example you can adapt:

import 'package:flutter/material.dart';
import 'package:chewie/chewie.dart';
import 'package:video_player/video_player.dart';

class VideoPlayerScreen extends StatefulWidget {
  const VideoPlayerScreen({Key? key}) : super(key: key);

  @override
  State<VideoPlayerScreen> createState() => _VideoPlayerScreenState();
}

class _VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindingObserver {
  late VideoPlayerController _videoController;
  late ChewieController _chewieController;
  bool _wasPlayingBeforeBackground = false; // Track playback state before app goes to background

  @override
  void initState() {
    super.initState();
    // Register the lifecycle observer
    WidgetsBinding.instance.addObserver(this);
    _setupVideoPlayer();
  }

  Future<void> _setupVideoPlayer() async {
    // Replace this with your video URL or local file path
    _videoController = VideoPlayerController.network(
      'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4',
    );
    
    await _videoController.initialize();
    
    _chewieController = ChewieController(
      videoPlayerController: _videoController,
      autoPlay: true,
      looping: true,
      // Add any other Chewie settings you need here
    );
    
    setState(() {});
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    
    switch (state) {
      case AppLifecycleState.paused:
        // App moved to background: pause video if it was playing
        if (_chewieController.isPlaying) {
          _wasPlayingBeforeBackground = true;
          _chewieController.pause();
        }
        break;
      case AppLifecycleState.resumed:
        // App back to foreground: resume if it was playing before
        if (_wasPlayingBeforeBackground) {
          _chewieController.play();
          _wasPlayingBeforeBackground = false;
        }
        break;
      // We don't need to handle inactive/detached states for this use case
      default:
        break;
    }
  }

  @override
  void dispose() {
    // Clean up resources to avoid memory leaks
    WidgetsBinding.instance.removeObserver(this);
    _videoController.dispose();
    _chewieController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Chewie Video Player')),
      body: Center(
        child: _videoController.value.isInitialized
            ? Chewie(controller: _chewieController)
            : const CircularProgressIndicator(),
      ),
    );
  }
}

Important Notes

  • Playback State Tracking: The _wasPlayingBeforeBackground variable ensures we don't resume playback if the user had manually paused the video before switching apps.
  • Resource Cleanup: Always dispose of the video controllers and remove the lifecycle observer in the dispose method—this prevents memory leaks in your app.
  • Testing: Try these scenarios to verify:
    • Open the video page: video starts playing automatically.
    • Switch to another app: video pauses right away.
    • Switch back to your app: video resumes if it was playing before.
    • Navigate to another screen in your app: video keeps playing (since the app is still in the foreground).

内容的提问来源于stack exchange,提问作者Abhijit Rajmane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 08:42:35