How to add a custom thumbnail image in chewie flutter?

custom thumbnail image in chewie flutter

Introduction

Videos are ubiquitous – they can transmit info faster than any other method. Playing videos directly within your application is becoming increasingly important, from YouTube and Instagram stories to application development classes.

The Chewie flutter bundle includes many features such as mute and unmute, video speed, autoplay, video controls, and so on. We may play videos from three sources with this package: network, assets, and file.

Implementation:

Step 1: Add the dependencies

environment:
  sdk: ">=2.6.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  chewie: ^0.12.2
  video_player: ^1.0.1
  video_thumbnail: ^0.2.5+1
  path_provider: ^1.6.28

Step 2: Import

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

Step 3: Add the internet permission

Add this to your project root

>/android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>

Step 4: Enable AndriodX

Add this to your gradle.properties file:

org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

Generate Thumbnails using video_thumbnail and path_provider package.

_generateThumbnail() async {
   String fileName = await VideoThumbnail.thumbnailFile(
     video: VIDEO_ONE,
     thumbnailPath: (await getTemporaryDirectory()).path,
     imageFormat: ImageFormat.PNG,
     maxHeight:
         350, // specify the height of the thumbnail, let the width auto-scaled to keep the source aspect ratio
     quality: 75,
   );
   final file = File(fileName);
   imageBytes = file.readAsBytesSync();
   print('----image--->>>$fileName');
   setState(() {});
 }

Setting up the variables

String VIDEO_ONE =
    "https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4";

VideoPlayerController videoPlayerController1;

ChewieController _chewieController1;

Uint8List imageBytes;

Initialize the Chewie chewie with a Video player video_thumbnail

Future<void> initializePlayer() async {
  if (mounted) {
    videoPlayerController1 = VideoPlayerController.network(VIDEO_ONE);

    await videoPlayerController1.initialize();
    _createChewieController();
    setState(() {});
  }
}

_createChewieController() {
  _chewieController1 = ChewieController(
    videoPlayerController: videoPlayerController1,
    aspectRatio: videoPlayerController1.value.aspectRatio,
    autoPlay: false,
    looping: true,
    allowFullScreen: true,
    allowedScreenSleep: false,
    autoInitialize: true,
  );
}

our initState and dispose methods

@override
void initState() {
  _generateThumbnail();

  initializePlayer();
  super.initState();
}

@override
void dispose() {
  videoPlayerController1.dispose();

  _chewieController1.dispose();

  super.dispose();
}

Here is our main work setting up the custom thumbnail see the example below for full action.

Container(
        width: MediaQuery.of(context).size.width,
        height: 350.0,
        padding: const EdgeInsets.all(12.0),
        color: Colors.lightBlue[50],
        child: Column(
          children: [
            Expanded(
              child: Center(
                child: _chewieController1 != null &&
                        _chewieController1
                            .videoPlayerController.value.initialized &&
                        _chewieController1.isPlaying
                    ? Chewie(
                        controller: _chewieController1,
                      )
                    : Stack(
                        children: [
                          imageBytes != null
                              ? Container(
                                  height: 350,
                                  width: MediaQuery.of(context).size.width,
                                  child: Image.memory(
                                    imageBytes,
                                    height: 350,
                                    width: MediaQuery.of(context).size.width,
                                  ),
                                )
                              : Container(
                                  height: 0,
                                  width: 0,
                                ),
                          _chewieController1 != null
                              ? Align(
                                  alignment: Alignment.center,
                                  child: ClipOval(
                                    child: Material(
                                      color: Colors.white, // Button color
                                      child: InkWell(
                                        splashColor:
                                            Colors.white, // Splash color
                                        onTap: () {
                                          _chewieController1.play();
                                          setState(() {});
                                        },
                                        child: SizedBox(
                                            width: 56,
                                            height: 56,
                                            child: Icon(Icons.play_arrow)),
                                      ),
                                    ),
                                  ),
                                )
                              : Align(
                                  alignment: Alignment.center,
                                  child: CircularProgressIndicator())
                        ],
                      ),
              ),
            ),
          ],
        ),
      ),

 

Full Code Implementation

import 'dart:async';
import 'dart:io';

import 'dart:typed_data';

import 'package:chewie/chewie.dart';
import 'package:flutter/foundation.dart';

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_player/video_player.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

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

  @override
  _VideoThumbState createState() => _VideoThumbState();
}

class _VideoThumbState extends State<VideoThumb> {
  String VIDEO_ONE =
      "https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4";

  VideoPlayerController videoPlayerController1;

  ChewieController _chewieController1;

  Uint8List imageBytes;

  @override
  void initState() {
    _generateThumbnail();

    initializePlayer();
    super.initState();
  }

  @override
  void dispose() {
    videoPlayerController1.dispose();

    _chewieController1.dispose();

    super.dispose();
  }

  _generateThumbnail() async {
    String fileName = await VideoThumbnail.thumbnailFile(
      video: VIDEO_ONE,
      thumbnailPath: (await getTemporaryDirectory()).path,
      imageFormat: ImageFormat.PNG,
      maxHeight:
          350, // specify the height of the thumbnail, let the width auto-scaled to keep the source aspect ratio
      quality: 75,
    );
    final file = File(fileName);
    imageBytes = file.readAsBytesSync();
    print('----image--->>>$fileName');
    setState(() {});
  }

  Future<void> initializePlayer() async {
    if (mounted) {
      videoPlayerController1 = VideoPlayerController.network(VIDEO_ONE);

      await videoPlayerController1.initialize();
      _createChewieController();
      setState(() {});
    }
  }

  _createChewieController() {
    _chewieController1 = ChewieController(
      videoPlayerController: videoPlayerController1,
      aspectRatio: videoPlayerController1.value.aspectRatio,
      autoPlay: false,
      looping: true,
      allowFullScreen: true,
      allowedScreenSleep: false,
      autoInitialize: true,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        title: Text("Video Thumnail",
            style: TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.w500,
                fontSize: 16.0)),
        centerTitle: false,
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: 350.0,
        padding: const EdgeInsets.all(12.0),
        color: Colors.lightBlue[50],
        child: Column(
          children: [
            Expanded(
              child: Center(
                child: _chewieController1 != null &&
                        _chewieController1
                            .videoPlayerController.value.initialized &&
                        _chewieController1.isPlaying
                    ? Chewie(
                        controller: _chewieController1,
                      )
                    : Stack(
                        children: [
                          imageBytes != null
                              ? Container(
                                  height: 350,
                                  width: MediaQuery.of(context).size.width,
                                  child: Image.memory(
                                    imageBytes,
                                    height: 350,
                                    width: MediaQuery.of(context).size.width,
                                  ),
                                )
                              : Container(
                                  height: 0,
                                  width: 0,
                                ),
                          _chewieController1 != null
                              ? Align(
                                  alignment: Alignment.center,
                                  child: ClipOval(
                                    child: Material(
                                      color: Colors.white, // Button color
                                      child: InkWell(
                                        splashColor:
                                            Colors.white, // Splash color
                                        onTap: () {
                                          _chewieController1.play();
                                          setState(() {});
                                        },
                                        child: SizedBox(
                                            width: 56,
                                            height: 56,
                                            child: Icon(Icons.play_arrow)),
                                      ),
                                    ),
                                  ),
                                )
                              : Align(
                                  alignment: Alignment.center,
                                  child: CircularProgressIndicator())
                        ],
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Conclusion:

In the post, I showed the fundamental framework of a video player in a flutter and how you can add a custom thumbnail image to a video player; you may alter this code to suit your needs.

Thank you 🎉

Leave a Comment