Flutter 视频video_player与缓存flutter_cache_manager

这里写自定义目录标题

    • [1. 依赖](#1. 依赖)
    • [2. 缓存flutter_cache_manager](#2. 缓存flutter_cache_manager)
    • [3. 视频video_player](#3. 视频video_player)

1. 依赖

dart 复制代码
  video_player: ^2.6.0
  flutter_cache_manager: ^3.3.1

2. 缓存flutter_cache_manager

参考官方DefaultCacheManager代码,这里引入Config可以指定天数与最大个数.

文件名 video_cache.dart

dart 复制代码
import 'package:flutter_cache_manager/flutter_cache_manager.dart';

/// The DefaultCacheManager that can be easily used directly. The code of
/// this implementation can be used as inspiration for more complex cache
/// managers.
class MyDefaultCacheManager extends CacheManager with ImageCacheManager {
  static const key = 'libCachedImageData';

  static final MyDefaultCacheManager _instance = MyDefaultCacheManager._();

  factory MyDefaultCacheManager() {
    return _instance;
  }

  MyDefaultCacheManager._()
      : super(Config(
          key,
          stalePeriod: const Duration(days: 7),
          maxNrOfCacheObjects: 20,
          repo: JsonCacheInfoRepository(databaseName: key),
          fileService: HttpFileService(),
        ));
}

3. 视频video_player

使用 await MyDefaultCacheManager().getSingleFile(url)) 即可

dart 复制代码
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'video_cache.dart';

// main.dart可以打开
// void main() {
//   runApp(MyApp());
// }

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late VideoPlayerController controller;
  bool isInitController = false;
  List mediaList = [
    {'type': 'video', 'url': 'https://static.ybhospital.net/test-video-10.MP4'},
    {
      'type': 'image',
      'url': 'https://img-home.csdnimg.cn/images/20230817060240.png'
    },
    {'type': 'video', 'url': 'https://static.ybhospital.net/test-video-6.mp4'},
    {'type': 'video', 'url': 'https://static.ybhospital.net/test-video-4.mp4'}
  ];
  int index = 0;

  @override
  void initState() {
    super.initState();
    initController();
  }

  initController() async {
    isInitController = false;
    controller = VideoPlayerController.file(
        await MyDefaultCacheManager().getSingleFile(mediaList[index]['url']))
      ..initialize().then((_) {
        setState(() {
          isInitController = true;
        });
        controller.addListener(_videoListener);
        controller.play();
      });
  }

  @override
  void dispose() {
    if (isInitController != false) {
      controller.removeListener(_videoListener);
      controller.dispose();
    }

    super.dispose();
  }

  _videoListener() {
    if (isInitController == false) return;

    if (controller.value.position == controller.value.duration) {
      next();
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Video Player Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: Center(
          child: Container(
            child: mediaList[index]['type'] == 'video'
                ? (isInitController
                    ? AspectRatio(
                        aspectRatio: controller.value.aspectRatio,
                        child: VideoPlayer(controller),
                      )
                    : Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: const [
                          CircularProgressIndicator(),
                          SizedBox(height: 20),
                          Text('Loading'),
                        ],
                      ))
                : Image.network(mediaList[index]['url']),
          ),
        ),
      ),
    );
  }

  next() {
    setState(() {
      if (isInitController != false && controller.value.isInitialized) {
        isInitController = false;
        controller.removeListener(_videoListener);
        controller.dispose();
      }

      index++;
      if (index >= mediaList.length) {
        index = 0;
      }

      if (mediaList[index]['type'] == 'video') {
        initController();
      } else {
        Future.delayed(Duration(seconds: 10), next);
      }
    });
  }

  void prev() {
    setState(() {
      if (index > 0) {
        index--;
      } else {
        index = mediaList.length - 1;
      }

      if (mediaList[index]['type'] == 'video') {
        initController();
      } else {
        Future.delayed(Duration(seconds: 10), next);
      }
    });
  }
}
相关推荐
煎饼小狗32 分钟前
Redis五大基本类型——Zset有序集合命令详解(命令用法详解+思维导图详解)
数据库·redis·缓存
旭日猎鹰2 小时前
Flutter踩坑记录(三)-- 更改入口执行文件
flutter
旭日猎鹰2 小时前
Flutter踩坑记录(一)debug运行生成的项目,不能手动点击运行
flutter
️ 邪神2 小时前
【Android、IOS、Flutter、鸿蒙、ReactNative 】自定义View
flutter·ios·鸿蒙·reactnative·anroid
雯0609~3 小时前
网页F12:缓存的使用(设值、取值、删除)
前端·缓存
简鹿办公3 小时前
如何提取某站 MV 视频中的音乐为 MP3 音频
音视频·简鹿视频格式转换器·视频提取mp3音频
yufengxinpian3 小时前
集成了高性能ARM Cortex-M0+处理器的一款SimpleLink 2.4 GHz无线模块-RF-BM-2340B1
单片机·嵌入式硬件·音视频·智能硬件
菠萝咕噜肉i5 小时前
超详细:Redis分布式锁
数据库·redis·分布式·缓存·分布式锁
runing_an_min5 小时前
ffmpeg视频滤镜:替换部分帧-freezeframes
ffmpeg·音视频·freezeframes
runing_an_min7 小时前
ffmpeg视频滤镜:提取缩略图-framestep
ffmpeg·音视频·framestep