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);
      }
    });
  }
}
相关推荐
华清远见IT开放实验室1 小时前
【项目案例】物联网比较好的10+练手项目推荐,附项目文档/源码/视频
物联网·音视频
码农郁郁久居人下5 小时前
Redis的配置与优化
数据库·redis·缓存
Hsu_kk7 小时前
Redis 主从复制配置教程
数据库·redis·缓存
DieSnowK7 小时前
[Redis][环境配置]详细讲解
数据库·redis·分布式·缓存·环境配置·新手向·详细讲解
AiFlutter8 小时前
Flutter之Package教程
flutter
比花花解语9 小时前
Java中Integer的缓存池是怎么实现的?
java·开发语言·缓存
Mingyueyixi12 小时前
Flutter Spacer引发的The ParentDataWidget Expanded(flex: 1) 惨案
前端·flutter
小东来13 小时前
电脑端视频剪辑软件哪个好用,十多款剪辑软件分享
音视频
cuijiecheng201816 小时前
音视频入门基础:AAC专题(8)——FFmpeg源码中计算AAC裸流AVStream的time_base的实现
ffmpeg·音视频·aac
Mr数据杨16 小时前
我的AI工具箱Tauri版-VideoIntroductionClipCut视频介绍混剪
人工智能·音视频