'Flutter use native Android & iOS YouTubePlayer to play videos
There are many packages out there on pub.dev which utilize the YouTube iFrame API to play YT-videos inline. But I cannot find a package which utilizes the native player, so I decided to create my own. But I'm struggling to get it working on Android. By implementing io.flutter.plugin.platform.PlatformView on Android and adding com.google.android.youtube.player.YouTubePlayerView to the View:
internal class YTNativeView(context: Context, id: Int, creationParams: Map<String?, Any?>?) : PlatformView, YouTubePlayer.OnInitializedListener {
private val ytPlayer = YouTubePlayerView(context)
private val apiKey = "<your-api-key>"
init {
ytPlayer.initialize(apiKey, this)
}
override fun getView(): View = ytPlayer
override fun dispose() {}
override fun onInitializationSuccess(provider: YouTubePlayer.Provider, youTubePlayer: YouTubePlayer, b: Boolean) {
youTubePlayer.loadVideo("QH2-TGUlwu4")
youTubePlayer.play()
}
override fun onInitializationFailure(provider: YouTubePlayer.Provider, youTubeInitializationResult: YouTubeInitializationResult) {}
}
the following error is thrown:
Unhandled Exception: PlatformException(error, java.lang.IllegalStateException: A YouTubePlayerView can only be created with an Activity which extends YouTubeBaseActivity as its context.
Then I tried to use com.google.android.youtube.player.YouTubePlayerFragment but I couldn't figure out how to properly build the view due to the lack of getFragmentManager(). Any ideas, solutions or hints?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
