• Flutter 视频video_player与缓存flutter_cache_manager


    1. 依赖

      video_player: ^2.6.0
      flutter_cache_manager: ^3.3.1
    
    • 1
    • 2

    2. 缓存flutter_cache_manager

    参考官方DefaultCacheManager代码,这里引入Config可以指定天数与最大个数.
    文件名 video_cache.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(),
            ));
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    3. 视频video_player

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

    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 {
      
      _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;
    
      
      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();
          });
      }
    
      
      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();
        }
      }
    
      
      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);
          }
        });
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
  • 相关阅读:
    spring cloud、gradle、父子项目、微服务框架搭建---cloud gateway(十)
    超分辨率提升IRN网络
    常用Win32 API的简单介绍
    【得到日期对象NSDate的各个部分 Objective-C语言】
    [附源码]java毕业设计病历管理系统设计
    WPF中可视化树和逻辑树的区别是什么
    ASP.NET Core 使用redis
    DGA行为转变引发了对网络安全的担忧
    RCE极限挑战
    郑州大学2022-2023第一学期算法设计与分析-实验3
  • 原文地址:https://blog.csdn.net/cookic12346/article/details/133375637