📘

【Flutter】VideoPlayerの備忘録

2021/07/12に公開

使用しているライブラリ

pubspec.yaml
video_player: ^2.1.10

https://pub.dev/packages/video_player

初期設定

ios/Runner/Info.plist
  <false/>
  <!-- ここから -->
  <key>NSAppTransportSecurity</key>
  <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
  </dict>
  <!-- ここまで -->
</dict>
</plist>

最後の<false/></dict></plist>の間に追記する

Info.plistを変更したため、一旦、flutter cleanを実行

実装

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  VideoPlayerController? _videoPlayerController;
  
  void initState() {
    super.initState();
    _videoPlayerController = VideoPlayerController.asset("assets/movies/sample.mp4")
      ..initialize().then((value) {
        _videoPlayerController!.play();
      });
  }

  
  void dispose() {
    super.dispose();
    _videoPlayerController!.dispose();
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      body: InkWell(
        onTap: () {
          setState(() {
            _videoPlayerController!.value.isPlaying ? _videoPlayerController!.pause() : _videoPlayerController!.play();
          });
        },
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: VideoPlayer(_videoPlayerController!),
        ),
      ),
    );
  }
}

Discussion