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:
dependencies:
youtube_player_flutter: ^8.1.2
Or just perform this command:
flutter pub add youtube_player_flutter
Then run:
flutter pub get
For Android, you need to set the minSdkVersion in your android/app/build.gradle file to at least 17 (20 or higher is strongly recommended).
If 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.
Check out the result:
Further reading:
- Flutter: SliverGrid example
- Best Libraries for Making HTTP Requests in Flutter
- Using GetX (Get) for Navigation and Routing in Flutter
- Flutter & Hive Database: CRUD Example
- Ways to Get a Random Item from a List in Dart (and Flutter)
- How to Check if a Variable is Null in Flutter and Dart
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.