Youtube Player in Flutter | Example of Youtube Player in Flutter

Flutter

Flutter Tutorial:

Introduction

Flutter

Why Flutter

About Flutter

Cross Platform

MVVM vs MVC vs MVP

Flutter Framework

Flutter Benefits

Flutter Comparison I

Flutter Comparison II

Flutter Comparison III

Install Flutter

Android studio vs VsCode

Android Setup

VsCode Setup

Vs Code Plugins

Android Studio Plugins

Flutter Widgets:

Flutter Basic Templates

Flutter Commands

Common Widgets

Top 10 popular widgets

Flutter Stateless vs Stateful

Type of Widgets

Flutter Text

Flutter Text Style

Textfield vs TextFormField

Flutter Scaffold

Flutter Container & SizedBox

Flutter Row & Column

Flutter Buttons

Flutter Stack

Flutter Forms

Flutter AlertDialog

Flutter Icons

Flutter Images

Flutter Drawer

Flutter ListView

Flutter GridView

Flutter Toast

Flutter Checkbox

Flutter Radio Button

Flutter Progress Bar

Flutter Tooltip

Flutter Slider

Flutter Table

Flutter SnackBar

Shimmer in Flutter

Bottom Navigation Bar

Flutter Gesture

Flutter Error Handling

Flutter DropDown

Flutter Toggle

Flutter Auto Close Keyboard

Flutter Screen Size

Flutter Advance

Custom Widget in Flutter

Flutter Navigator

Flutter Read Json

Flutter Generate Excel

Flutter Multiple Widgets

Flutter Bottom sheet

Flutter Copy to Clipboard

Flutter Tab bar

Flutter Code Editor

Flutter youtube Player

Flutter REST API

Flutter http

Flutter dio

dio vs http

Advanced Concepts

Tips Flutter App Development

Flutter App version Update

Flutter Copy Text in App

Flutter Handle Null Value

Flutter Splash Screen

Flutter Disposable

Notification Listener

Flutter Switch Cases

Flutter Slivers

Flutter Custom Appbar

Databinding in Flutter

Flutter Cards

Wrap vs Builder vs OverBarFlow

Flutter App Upgrade

GoogleMap vs FlutterMap

Circular progress contain Icon

DropDown Timer in Flutter

Flutter State management Comparison

Flutter vs Other Framework

Flutter Mixin

Flutter Database

Flutter Database

Suitable DB for Flutter

DBs for Flutter

Backend for flutter

SharedPreferences

Flutter Token Expired Handling

Flutter Provider

Flutter Provider Tutorial

Flutter GetX

Flutter GetX tutorial

Flutter with Native

Flutter FFI

Flutter Testing

Pass values in Flutter

WorkManager

Flutter Tips:

Best Practices

Reduce Flutter Screens

Tips to make app smart

Optimize App

Handle Multiple Pages

Interview Questions

Top 10 Interview Questions

Dart Interview Questions

Flutter 100 Interview Questions

Flutter 20 Interview Questions

Provider Interview Questions

GetX interview Questions

BLoC interview Questions

Youtube Player Example in Flutter

Youtube Player in Flutter

To integrate a YouTube player in your Flutter app, you can use the youtube_player_flutter package. Here’s an example of how to use it:

Run this command in terminal 
flutter pub add youtube_player_iframe

or 

#add in pubspec.yaml
youtube_player_iframe: # add latest version

Example of Youtube Player in Flutter

import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:youtube_player_iframe/youtube_player_iframe.dart';
import 'package:flutter/material.dart';
import 'package:rttutorials/yoube_ifram.dart';

// below are sample videos ids
const List<String> _videoIds = [
  'tcodrIK2P_I',
  'H5v3kku4y6Q',
  'nPt8bK2gbaU',
  'K18cpp_-gP8',
  'iLnmTe5Q2Qw',
  '_WoCV4c6XOE',
  'KmzdUe0RSJo',
  '6jZDSSZZxjQ',
  'p2lYr3vM_1w',
  '7QUtEmBT_-w',
  '34_PXCzGw1M'
];

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ResearchThinker',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: YoutubeAppDemo(),//ResearchThinkerExample(),
    );
  }
}


class YoutubeAppDemo extends StatefulWidget {
  @override
  _YoutubeAppDemoState createState() => _YoutubeAppDemoState();
}

class _YoutubeAppDemoState extends State<YoutubeAppDemo> {

//Here you declare youtube player controller
  late YoutubePlayerController _controller;

  @override
  void initState() {
    super.initState();
//Here you can pass additional parameters
    _controller = YoutubePlayerController(
      params: const YoutubePlayerParams(
        showControls: true,
        mute: false,
        showFullscreenButton: true,
        loop: false,
      ),
    );

    _controller.setFullScreenListener(
          (isFullScreen) {
        log('${isFullScreen ? 'Entered' : 'Exited'} Fullscreen.');
      },
    );

    _controller.loadPlaylist(
      list: _videoIds,
      listType: ListType.playlist,
      startSeconds: 136,
    );
  }

  @override
  Widget build(BuildContext context) {
    return YoutubePlayerScaffold(
      controller: _controller,
      builder: (context, player) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('ResearchThinker Youtube Demo'),
            actions: const [VideoPlaylistIconButton()],
          ),
          body: LayoutBuilder(
            builder: (context, constraints) {
              if (kIsWeb && constraints.maxWidth > 750) {
                return Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      flex: 3,
                      child: Column(
                        children: [
                          player,
                          const VideoPositionIndicator(),
                        ],
                      ),
                    ),
                    const Expanded(
                      flex: 2,
                      child: SingleChildScrollView(
                        child: Controls(),
                      ),
                    ),
                  ],
                );
              }

              return ListView(
                children: [
                  player,
                  const VideoPositionIndicator(),
                  const Controls(),
                ],
              );
            },
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    _controller.close();
    super.dispose();
  }
}

///
class Controls extends StatelessWidget {
  ///
  const Controls();

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // MetaDataSection(),
          // _space,
          // SourceInputSection(),
          // _space,
          // PlayPauseButtonBar(),
          _space,
          const VideoPositionSeeker(),
          _space,
          // PlayerStateSection(),
        ],
      ),
    );
  }

  Widget get _space => const SizedBox(height: 10);
}

///
class VideoPlaylistIconButton extends StatelessWidget {
  ///
  const VideoPlaylistIconButton({super.key});

  @override
  Widget build(BuildContext context) {
    final controller = context.ytController;

    return IconButton(
      onPressed: () async {
        controller.pauseVideo();
        await Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => const VideoListPage(),
          ),
        );
        controller.playVideo();
      },
      icon: const Icon(Icons.playlist_play_sharp),
    );
  }
}

///
class VideoPositionIndicator extends StatelessWidget {
  ///
  const VideoPositionIndicator({super.key});

  @override
  Widget build(BuildContext context) {
    final controller = context.ytController;

    return StreamBuilder<YoutubeVideoState>(
      stream: controller.videoStateStream,
      initialData: const YoutubeVideoState(),
      builder: (context, snapshot) {
        final position = snapshot.data?.position.inMilliseconds ?? 0;
        final duration = controller.metadata.duration.inMilliseconds;

        return LinearProgressIndicator(
          value: duration == 0 ? 0 : position / duration,
          minHeight: 1,
        );
      },
    );
  }
}

///
class VideoPositionSeeker extends StatelessWidget {
  ///
  const VideoPositionSeeker({super.key});

  @override
  Widget build(BuildContext context) {
    var value = 0.0;

    return Row(
      children: [
        const Text(
          'Seek',
          style: TextStyle(fontWeight: FontWeight.w300),
        ),
        const SizedBox(width: 14),
        Expanded(
          child: StreamBuilder<YoutubeVideoState>(
            stream: context.ytController.videoStateStream,
            initialData: const YoutubeVideoState(),
            builder: (context, snapshot) {
              final position = snapshot.data?.position.inSeconds ?? 0;
              final duration = context.ytController.metadata.duration.inSeconds;

              value = position == 0 || duration == 0 ? 0 : position / duration;

              return StatefulBuilder(
                builder: (context, setState) {
                  return Slider(
                    value: value,
                    onChanged: (positionFraction) {
                      value = positionFraction;
                      setState(() {});

                      context.ytController.seekTo(
                        seconds: (value * duration).toDouble(),
                        allowSeekAhead: true,
                      );
                    },
                    min: 0,
                    max: 1,
                  );
                },
              );
            },
          ),
        ),
      ],
    );
  }
}

class VideoListPage extends StatefulWidget {
  ///
  const VideoListPage({super.key});

  @override
  State<VideoListPage> createState() => _VideoListPageState();
}

class _VideoListPageState extends State<VideoListPage> {
  late final List<YoutubePlayerController> _controllers;

  @override
  void initState() {
    super.initState();

    _controllers = List.generate(
      _videoIds.length,
          (index) => YoutubePlayerController.fromVideoId(
        videoId: _videoIds[index],
        autoPlay: false,
        params: const YoutubePlayerParams(showFullscreenButton: true),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('ResearchThinker Video List Demo'),
      ),
      body: ListView.separated(
        padding: const EdgeInsets.all(8),
        itemCount: _controllers.length,
        itemBuilder: (context, index) {
          final controller = _controllers[index];

          return Card(
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: YoutubePlayer(
                key: ObjectKey(controller),
                aspectRatio: 16 / 9,
                enableFullScreenOnVerticalDrag: false,
                controller: controller
                  ..setFullScreenListener(
                        (_) async {
                      final videoData = await controller.videoData;
                      final startSeconds = await controller.currentTime;

                      final currentTime = await FullscreenYoutubePlayer.launch(
                        context,
                        videoId: videoData.videoId,
                        startSeconds: startSeconds,
                      );

                      if (currentTime != null) {
                        controller.seekTo(seconds: currentTime);
                      }
                    },
                  ),
              ),
            ),
          );
        },
        separatorBuilder: (context, _) => const SizedBox(height: 16),
      ),
    );
  }

  @override
  void dispose() {
    for (final controller in _controllers) {
      controller.close();
    }

    super.dispose();
  }
}

Replace ‘_videoIds‘ with the actual YouTube video ID , which you want to play.

If you face any issue, please comment below, we will reply soon

Leave a Reply

Your email address will not be published. Required fields are marked *

web_horizontal
About Us ♢ Disclaimer ♢ Privacy Policy ♢ Terms & Conditions ♢ Contact Us

Copyright © 2023 ResearchThinker.com. All rights reserved.