10.7 C
New York
Tuesday, December 6, 2022

How to embed Youtube video in Flutter

This straightforward, concise tutorial shows you how to embed a Youtube video into a Flutter mobile app. We’ll use youtube_player_flutter, one of the most popular packages for this stuff.

Setting up the plugin

Add this to the dependencies block in your pubspec.yaml file: Advertisements

dependencies:
  youtube_player_flutter: ^8.0.0

Or just perform this command:

flutter pub add youtube_player_flutter

Then run:

flutter pub get

For Android, you need to set minSdkVersion of your android/app/build.gradle file to at least 17 (20 or higher is strongly recommended).

AdvertisementsIf you’re building an app for iOS devices and using an old version of the plugin (7.x or older), you have to add the following to your ./ios/Runner/info.plist file:

<key>io.flutter.embedded_views_preview</key>
<true/>

Screenshot:

The Complete Example

Replace all of the default code in ./lib/main.dart with this:

import 'package:flutter/material.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,

      title: 'Flutter Example',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  static String myVideoId = 'PQSagzssvUQ';
  // the full url: https://www.youtube.com/watch?v=PQSagzssvUQ&ab_channel=NASA
  // it's an interesting video from NASA on Youtube

  // Initiate the Youtube player controller
  final YoutubePlayerController _controller = YoutubePlayerController(
    initialVideoId: myVideoId,
    flags: const YoutubePlayerFlags(
      autoPlay: true,
      mute: false,
    ),
  );

  MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Flutter and Youtube'),
        ),
        body: YoutubePlayer(
          controller: _controller,
          liveUIColor: Colors.amber,
        ));
  }
}

After all, restart your simulators and your Flutter app (if it’s already running). A hot reload or a hot restart may not work.

Advertisements

Check out the result:

Further reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles