Flutter TV App - Video Player example

Last updated Sep 01, 2021

In this flutter tv app example we will learn how to play videos inside tv app. To play videos in Flutter TV app we are using the video_player plugin. In this example we will cover

  • Parse json data
  • Display List inside Listview
  • Play Video with TV Video Player

 

Before implement video player example we read about how to create Flutter TV Application in my previous article

 

Let's get started

 

Download Source code

 

Step 1: Create Flutter Application

Step 2:  Add required pubspec.yaml file

dev_dependencies:
  flutter_test:
    sdk: flutter

  video_player: ^2.1.14

 

Step 3: Parse json data

We are adding sample video json data in video.dart file. To read this json data we are creating the model classes

 

class Channel{
  String title;
  String description;
  String thumb;
  List sources;
  Channel({required this.title,required this.description,required this.thumb,required this.sources});

   factory Channel.fromJson(Map<dynamic,dynamic> json){

    return Channel(
      title:json['title'],
      description:json['description'],
      thumb:json['thumb'],
      sources:json['sources'],
    );
  }
}

class ChannelsList{

  List channels;
  ChannelsList(this.channels);

  factory ChannelsList.fromJson(Map<dynamic,dynamic> json){
    var list=List.empty(growable: true);
    if (json['videos'] != null) {
      json['videos'].forEach((v) {
        final model = Channel.fromJson(v);
        list.add(model);
      });
    }
    return ChannelsList(list);
  }
}

 

 

To parse json data into model class will be done by

Future> loadChannels(){
    return Future.value(ChannelsList.fromJson(mediaJSON).channels);
}

 

Step 4: Display List data

 FutureBuilder(
  future: loadChannels(),
  builder: (BuildContext context, AsyncSnapshot> snapshot) {
    if(snapshot!.hasData)
      {
        var list=snapshot.data;
        return ListView.builder(
            itemCount: (list==null)?0:snapshot.data!.length,
            itemBuilder: (item,index){
          return MaterialButton(onPressed:(){
            Navigator.push(context, MaterialPageRoute(builder: (context){
              return MyTvScreen(url:snapshot.data![index].sources[0]);
            }));
          },child: Card(child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: ListTile(leading:Image.network("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/${snapshot.data![index].thumb}",height:100),title:Text(snapshot.data![index].title ),),
          )));
        });
      }
    return Container();
  },

),

 

Step 5: Play videos

To play videos to tv app we have creaetd  a widget which will contains the VideoPlayer widget. This video player widget internally use the exoplayer plugin

/// Widget that displays the video controlled by [controller].
class VideoPlayer extends StatefulWidget {
  /// Uses the given [controller] for all video rendered in this widget.
  VideoPlayer(this.controller);

  /// The [VideoPlayerController] responsible for the video being rendered in
  /// this widget.
  final VideoPlayerController controller;

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

 

Step 6: Let's run the application

 

Flutter TV app with video player

 

 

Complete code for Flutter TV app video Player

import 'package:flutter/material.dart';

import 'package:video_player/video_player.dart';
class MyTvScreen extends StatefulWidget {

  final String url;
  MyTvScreen({required this.url});
  @override
  _MyTvScreenState createState() => _MyTvScreenState();
}
class _MyTvScreenState extends State {
  late VideoPlayerController _controller;


  @override
  void initState() {
    _controller = VideoPlayerController.network(widget.url);
    _controller.addListener(() {
      setState(() {});
    });
    _controller.setLooping(true);
    _controller.initialize().then((_) => setState(() {}));
    _controller.play();
  }
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("TV Player"),
      ),
      body: SingleChildScrollView(
        child: Stack(
          alignment: Alignment.bottomCenter,
          children: [
            Container(child: VideoPlayer(_controller),height:400,width: double.infinity,),
            _ControlsOverlay(controller: _controller),
            VideoProgressIndicator(_controller, allowScrubbing: true),


          ],
        ),
      ),

    );
  }

}
class _ControlsOverlay extends StatelessWidget {
  const _ControlsOverlay({Key? key, required this.controller})
      : super(key: key);

  static const _examplePlaybackRates = [
    0.25,
    0.5,
    1.0,
    1.5,
    2.0,
    3.0,
    5.0,
    10.0,
  ];

  final VideoPlayerController controller;

  @override
  Widget build(BuildContext context) {
    return  Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        Container(
          color: Colors.black26,
          height: 50,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: AnimatedSwitcher(
              duration: Duration(milliseconds: 50),
              reverseDuration: Duration(milliseconds: 200),
              child: Row(
                children: [
                  MaterialButton(
                    onPressed: () async{
                      var position=   await controller.position;

                      controller.seekTo(Duration(seconds: position!.inSeconds-5));
                    },
                    child: Icon(
                      Icons.arrow_back_ios,
                      color: Colors.white,
                      size: 20.0,
                    ),
                  ),
                  SizedBox(width: 20,),
                  controller.value.isPlaying
                      ? MaterialButton(
                    child: Icon(
                      Icons.pause,
                      color: Colors.white,
                      size: 30.0,
                    ),
                    onPressed: () {
                      controller.value.isPlaying ? controller.pause() : controller.play();
                    },
                  )
                      : MaterialButton(
                    child: Icon(
                      Icons.play_arrow,
                      color: Colors.white,
                      size: 30.0,
                    ),
                    onPressed: () {
                      controller.value.isPlaying ? controller.pause() : controller.play();
                    },
                  ),
                  SizedBox(width: 20,),
                  MaterialButton(
                    onPressed: () async{
                      var position=   await controller.position;

                      controller.seekTo(Duration(seconds: position!.inSeconds+5));
                    },
                    child: Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.white,
                      size: 20.0,
                    ),
                  ),
                  SizedBox(width: 20,),
                  PopupMenuButton(
                    initialValue: controller.value.playbackSpeed,
                    tooltip: 'Playback speed',
                    color: Colors.white,
                    onSelected: (speed) {
                      controller.setPlaybackSpeed(speed);
                    },
                    itemBuilder: (context) {
                      return [
                        for (final speed in _examplePlaybackRates)
                          PopupMenuItem(
                            value: speed,
                            child: Text('${speed}x',),
                          )
                      ];
                    },
                    child: Text('${controller.value.playbackSpeed}x',style: TextStyle(color: Colors.white),),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );

  }
}

 

Conclusion:

In this Flutter TV app example we covered how to parse json data and play videos inside video player for flutter tv application

 

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

3803 Views