Design Converter
Education
Software Development Executive - II
Last updated on Sep 10, 2024
Last updated on Sep 8, 2023
With the advent of modern app development, displaying videos is becoming increasingly required. Flutter apps aren't an exception. For implementing video playback, the development team at Flutter offers the video_player plugin, a beneficial tool that offers developers the ability to incorporate videos from various sources - whether they are stored on the file system, bundled in as an asset, or retrieved from the internet.
The Flutter video player has nuanced implementations depending on the device platform. For iOS, it leverages the AVPlayer to handle playback, while, on Android, it makes use of ExoPlayer. In this guide, we'll delve into and discuss the Flutter video player's basic features, providing a step-by-step approach to stream a video over the internet, with simple play and pause controls.
Before we kickstart our journey into Flutter's video world, it's essential to first set up the Flutter environment for video playback.
To work with Flutter video, first add the video_player plugin as a dependency in your project. You can do this by running the flutter pub add command as follows:
1 flutter pub add video_player 2
The command above tells flutter to find and download the video player resources, along with other Flutter packages required for the app.
Next up, let's configure our Android and iOS settings by adding the necessary permissions to stream videos from the internet.
Open the AndroidManifest.xml file situated in <project root>/android/app/src/main/
. Add the permission just after the <application>
definition.
1 <manifest xmlns:android="http://schemas.android.com/apk/res/android"> 2 <application ...> 3 4 </application> 5 6 <uses-permission android:name="android.permission.INTERNET"/> 7 </manifest> 8
For iOS, make the changes in the Info.plist file found at <project root>/ios/Runner/
.
1 <key>NSAppTransportSecurity</key> 2 <dict> 3 <key>NSAllowsArbitraryLoads</key> 4 <true/> 5 </dict> 6
Playing videos in Flutter entails creating and initializing a VideoPlayerController. This nifty controller establishes a connection with the video and prepares it for playback.
In this section, we'll build a StatefulWidget that stores a VideoPlayerController and the Future returned by VideoPlayerController.initialize. We'll initialize the controller in the initState method and dispose of it in the dispose method.
To do this, we will create a StatefulWidget VideoPlayerScreen and a companion VideoPlayerScreenState State class. Inside VideoPlayerScreenState, we'll define a VideoPlayerController and a Future object that calls our initialize method. In initState we define our controller and the _initializeVideoPlayerFuture. In dispose, we ensure that we dispose of the controller to free up resources.
Here's the appropriate Dart code for the setup:
1 class VideoPlayerScreen extends StatefulWidget { 2 const VideoPlayerScreen({super.key}); 3 4 @override 5 State<VideoPlayerScreen> createState() => _VideoPlayerScreenState(); 6 } 7 8 class _VideoPlayerScreenState extends State<VideoPlayerScreen> { 9 late VideoPlayerController _controller; 10 late Future<void> _initializeVideoPlayerFuture; 11 12 @override 13 void initState() { 14 super.initState(); 15 16 _controller = VideoPlayerController.networkUrl( 17 Uri.parse( 18 'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4', 19 ), 20 ); 21 22 _initializeVideoPlayerFuture = _controller.initialize(); 23 } 24 25 @override 26 void dispose() { 27 _controller.dispose(); 28 super.dispose(); 29 } 30 31 @override 32 Widget build(BuildContext context) { 33 return Container(); 34 } 35 } 36
Now that we've initialized the VideoPlayerController, it's time to display our video content. Flutter provides a VideoPlayer widget to show the video from our controller. By default, this widget expands as much as possible, which might not be ideal for maintaining the aspect ratio of a video.
To remedy this, we pair it with an AspectRatio widget to ensure our video content maintains the proper proportions.
Let's see how we can create a UI for our video player:
1 FutureBuilder( 2 future: _initializeVideoPlayerFuture, 3 builder: (context, snapshot) { 4 if (snapshot.connectionState == ConnectionState.done) { 5 return AspectRatio( 6 aspectRatio: _controller.value.aspectRatio, 7 child: VideoPlayer(_controller), 8 ); 9 } else { 10 return const Center( 11 child: CircularProgressIndicator(), 12 ); 13 } 14 }, 15 ); 16
In this example, a FutureBuilder is used to display a loading spinner while we wait for the VideoPlayerController to finish initialization.
Now that we are playing videos in our Flutter app, let's explore how we can control our video playback.
By default, a video starts in a paused state when loaded. We can facilitate video playback by employing the play method provided by the VideoPlayerController. Likewise, the pause method is used to pause the video.
Let's add a FloatingActionButton to our app that displays an icon based on the current playback state of our video. This button will also act as our play/pause control, allowing the user to toggle video playback at their convenience.
Here is how to implement the play and pause functions:
1 FloatingActionButton( 2 onPressed: () { 3 setState(() { 4 if (_controller.value.isPlaying) { 5 _controller.pause(); 6 } else { 7 _controller.play(); 8 } 9 }); 10 }, 11 child: Icon( 12 _controller.value.isPlaying ? Icons.pause : Icons.play_arrow, 13 ), 14 ) 15
In this FloatingActionButton, we have set the onPressed function to call play or pause based on the current playback state. By wrapping play or pause with a setState, we ensure that the correct icon is shown, with a pause icon when playing and a play icon when paused.
Now, let's assemble all the bits and pieces we've discussed so far and create a video player demo program. This program includes a StatefulWidget, a VideoPlayerController, aspectRatio widgets display, and finally, a play-pause FloatingActionButton.
Setting up and controlling video playback in Flutter is an exhilarating experience, isn't it? This is all because of the power of Flutter and Dart software development. In a nutshell, this easy to read and understand example encapsulates the topics we've discussed about controlling video playback.
Flutter doesn't limit you to just playing, pausing, and displaying videos. With the power of the VideoPlayerController, you can control various other aspects such as volume, playback speed, and even display subtitled content or live streaming videos! Furthermore, Flutter allows more granular control that gives the user a smooth and intuitive video consumption experience, accentuating the user interaction within your app.
By using other handy methods provided by VideoPlayerController, you can:
These additional controls add a new dimension to the user experience, which might be useful depending on your app requirements. You have a powerful tool at your disposal to deliver a user-friendly, highly customizable video experience within your Flutter applications.
As developers, we know that things don't always go as planned. There could be various issues when dealing with video playback runs, and it's crucial to account for these potential problems and handle them gracefully.
The VideoPlayerController has an onError callback which is triggered when an error occurs during video playback. You can customize this callback to display a custom error message or perform specific actions depending on the type of error.
1 _controller = VideoPlayerController.networkUrl( 2 Uri.parse('https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4'), 3 )..initialize().catchError((error) { 4 // Handle error 5 print("Error loading video : $error"); 6 }); 7
In the Dart code snippet above, any error during video initialization triggers the catchError method, which will print the error. You can customize this block to handle errors as per your app's requirements.
There are multiple ways Flutter allows you to enhance the video experience for your users further. For instance, you can create a fullscreen video player or even build your own custom video player widget with its unique controls.
If your app's nature demands more space to play videos, going full screen can be the perfect solution. You can use the Flexible widget in combination with SystemChrome.setPreferredOrientations to create a more immersive and engaging video player experience in Flutter.
With Flutter, you don't have to be confined to the default video player controls. You have the flexibility to build your widget for user interaction with the video. Depending on your application, you may want to incorporate unique features or control designs, such as tap to mute, double tap to fullscreen, swipe for playback speed control, and more.
Delivering a smooth video playback experience is crucial for user satisfaction. In the world of app development, especially with media-rich applications, there are several performance factors to keep in mind.
To ensure that the videos don't start with a buffering screen, you can pre-buffer the videos if they fit well within memory limits. The video player plugin also provides callbacks like bufferingStart and bufferingEnd to customize the user interface during buffering times.
For apps that are highly reliant on videos, controlling memory usage and bandwidth consumption becomes crucial. You can control these aspects by adjusting the video quality, implementing video compression and optimization techniques, loading videos over efficient networking protocols, and managing app resources effectively.
As with any feature in app development, it's crucial to thoroughly test video playback to ensure a smooth user experience. Moreover, knowing how to debug issues is essential when dealing with rich media like videos in Flutter.
When a video doesn't play as expected, you can use various strategies to debug the issues. The video_player plugin's value property provides a wealth of information that can help in debugging. You can view details such as the video's duration, current playback position, buffering status, error description, and more.
In addition to this, Flutter offers sophisticated debugging tools that help in diagnosing other potential issues, such as UI layout problems, performance issues, and more.
In Flutter, you can perform unit tests on your video-related widgets and classes to ensure they work as expected. Widget testing allows you to create a test widget, pump it into the widget tree, and then interact with it as a user would.
It's good practice to test all edge case scenarios with your video player, including screen rotation changes, network connectivity changes, and other aspects to ensure a seamless user experience.
By now, you should have a solid understanding of the capabilities of the VideoPlayer plugin in Flutter. We've examined how to integrate and control video playback, add advanced video features, handle video errors, and even delve into performance considerations.
Whether you're developing a social media app, an online learning platform, or any application that uses video, Flutter's versatility and ease of use make it easier to provide an enriching, interactive, and seamless video experience to your users. With Flutter, delivering top-notch video experiences is straightforward and within the grasp of every developer.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.