Embedding a Youtube video in Flutter Web - flutter

Is it possible to embed a Youtube video in a Flutter web page? I tried the following code to have a Youtube embedded in my Flutter website, but nothing appears on the page without any error message.
import 'package:flutter_html_view/flutter_html_view.dart';
Container(child: HtmlView(data: """
<iframe src="https://www.youtube.com/embed/xMzkWfIR9Pk" width="560" height="315"></iframe>
""")),
Also tried the solution recommended here (WebView in Flutter Web) but that doesn't work either.
import 'dart:ui' as ui
//ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
'hello-world-html',
(int viewId) => html.IFrameElement()
..width = '640'
..height = '360'
..src = 'https://www.youtube.com/embed/IyFZznAk69U'
..style.border = 'none');

I used to package called flutter_html
But this gave me some scrolling issues.
Html(
data: '<iframe width="560" height="315" src="https://www.youtube.com/embed/D_mCZlQZg9Y" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>',
)

You should go like this
import 'dart:html' as html;
import 'dart:js' as js;
import 'dart:ui' as ui;
String viewID = "your-view-id";
#override
Widget build(BuildContext context) {
// ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
viewID,
(int id) => html.IFrameElement()
..width = MediaQuery.of(context).size.width.toString()
..height = MediaQuery.of(context).size.height.toString()
..src = 'https://www.youtube.com/embed/IyFZznAk69U'
..style.border = 'none');
return SizedBox(
height: 500,
child: HtmlElementView(
viewType: viewID,
),
);
}

You can use the youtube_player_iframe
YoutubePlayerController _controller = YoutubePlayerController(
initialVideoId: 'K18cpp_-gP8',
params: YoutubePlayerParams(
playlist: ['nPt8bK2gbaU', 'gQDByCdjUXw'], // Defining custom playlist
startAt: Duration(seconds: 30),
showControls: true,
showFullscreenButton: true,
),
);
YoutubePlayerIFrame(
controller: _controller,
aspectRatio: 16 / 9,
),

ext_video_player supports Android, iOS and web for YouTube. You can try running sample code from ext_video_player repo.
I tested with different browsers of different OS. Android, Mac, Windows browsers are working fine with ext_video_player. But it's not playing with iOS browser.

There are, at least, two solutions:
a) video_player package now works fine in the three main platforms: android, ios and web
b) This article explains a good way to embed video source in a flutter web widget, even when the article is for local files, the final procedure works fine for web sources, like youtube, too: https://vermahitesh.medium.com/play-local-video-on-flutter-web-d757bab0141c

Related

Calling postMessage on iframeElement in flutter web

I have a flutter web application. I need to call postMessage to be handled by the page opened in an iframe element using
ui.platformViewRegistry.registerViewFactory(
'hello-world-html',
(int viewId) => html.IFrameElement()
..width = '100%'
..height = '100%'
..src = widget.url
..style.border = 'none'
);
Is there a way to do this?
Technically, PostMessage sends to the main document's window, not to the iframe's.
Specify the iframe's window object in Javascript:
document.getElementById('hello-world-html').contentWindow.postMessage(.......)
or in Dart you can do:
import 'dart:html' as html;
// Your code
html.document.getElementById.getElementById('hello-world-html').contentWindow.postMessage(.......)
this works for an iframe that has a cross domain src
import 'dart:html';
IFrameElement element = document.getElementById('iframe') as IFrameElement;
element.contentWindow?.postMessage(data.toJson(),'*');

Is there AdMob support for Flutter web?

Is there AdMob support for Flutter web? All libraries that I found are intended only for Android and IOS
As you can see in the image below, Google Admobe is not supported for the web so you can not use it for flutter web or other web frameworks.
On other hand, you can use adsense and set your ads for flutter web,
and I find this solution for using Adsense as HTML(with IFrameElement)
first created an html file adview.html
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:inline-block;width:320px;height:80px"
data-ad-client="ca-pub-xxxxxx"
data-ad-slot="xxxxxxx"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
And then, an IFrameElement to make use of the HTML:
import 'dart:html';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
Widget adsenseAdsView() {
// ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
'adViewType',
(int viewID) => IFrameElement()
..width = '320'
..height = '100'
..src = 'adview.html'
..style.border = 'none');
return SizedBox(
height: 100.0,
width: 320.0,
child: HtmlElementView(
viewType: 'adViewType',
),
);
}
firebase_admob is now deprecated in favour of google_mobile_ads and both of them do not support flutter web. However, you can use display ads on websites using Google Adsense.
You can create a blank web page and add ads and embed the flutter app in the HTML page.
Ref:
Google Adsense
Embed flutter App in website

Problem in google login in canva through webview in flutter

I wanted to upload pics through canva from my flutter app that is why I am using the flutter-webview-plugin for the first time and therefore I am not able to solve this issue.
Code for the same is:-
import 'package:flutter/material.dart';
import 'package:kf_drawer/kf_drawer.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:async';
class SettingsPage extends KFDrawerContent {
#override
_SettingsPageState createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
final Completer<WebViewController> _controller =
Completer<WebViewController>();
#override
Widget build(BuildContext context) {
return SafeArea(
child: Center(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
....
],
),
Expanded(
child: Container(
height: 500,
child: WebView(
initialUrl: "https://shree-hari.github.io/laxmi_canva/index.html",
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController){
_controller.complete(webViewController);
},
),
),
)
],
),
),
);
}
}
Please Help me to address this issue 🙄.
Google not allow native Flutter Web-Views to initiate OAuth.
For more info read Google Blog
In your case, I can suggest 3 Possible Solutions.
Try to Sign in with Email/Password instead of Google Sign In.
Use url_launcher to redirect the user to the browser.
If you don't want the user to leave your app
then you can use flutter_custom_tabs
this plugin use Chrome Custom Tabs to create a native experience inside the Flutter App.
You can add this userAgent :
WebView(
initialUrl: url,
userAgent: Platform.isIOS ? 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_1_2 like Mac OS X) AppleWebKit/605.1.15' +
' (KHTML, like Gecko) Version/13.0.1 Mobile/15E148 Safari/604.1' :
'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Mobile Safari/537.36',
...
Use this package, it works like a charm
https://github.com/LinusU/flutter_web_auth
In the background, this plugin uses ASWebAuthenticationSession on iOS 12+ and macOS 10.15+, SFAuthenticationSession on iOS 11, Chrome Custom Tabs on Android and opens a new window on Web.
Your auth flow must land in the scheme you provide in callbackUrlScheme property. Then just parse the callback url and implement you own business logic around signin/signup
import 'package:flutter_web_auth/flutter_web_auth.dart';
// Present the dialog to the user
final result = await FlutterWebAuth.authenticate(url: "https://my-custom-app.com/connect", callbackUrlScheme: "my-custom-app");
// Extract token from resulting url
final token = Uri.parse(result).queryParameters['token']
https://stackoverflow.com/a/71297966/18723243
Using webview_flutter package you can fix the problem by adding userAgent: 'random', in the web view constructor. So, it will look like this:
WebView(
userAgent: 'random',
)

Cache in GrapghQl Flutter package settings and how to check it works

I'm trying to implement graphQl Flutter package in my app.
https://github.com/zino-app/graphql-flutter
Everything works well, but I have some issues with cache.
If we ran example from this package https://github.com/zino-app/graphql-flutter/tree/master/packages/graphql_flutter/example we can see that cache doesn't work.
In my app I also can't increase speed, it always get data online.
The code from this example
class GraphQLWidgetScreen extends StatelessWidget {
const GraphQLWidgetScreen() : super();
#override
Widget build(BuildContext context) {
final HttpLink httpLink = HttpLink(
uri: 'https://api.github.com/graphql',
);
final AuthLink authLink = AuthLink(
// ignore: undefined_identifier
getToken: () async => 'Bearer $YOUR_TOKEN',
);
Link link = authLink.concat(httpLink);
if (ENABLE_WEBSOCKETS) {
final WebSocketLink websocketLink = WebSocketLink(
url: 'ws://localhost:8080/ws/graphql',
config: SocketClientConfig(
autoReconnect: true, inactivityTimeout: Duration(seconds: 15)),
);
link = link.concat(websocketLink);
}
final ValueNotifier<GraphQLClient> client = ValueNotifier<GraphQLClient>(
GraphQLClient(
cache: OptimisticCache(
dataIdFromObject: typenameDataIdFromObject,
),
link: link,
),
);
return GraphQLProvider(
client: client,
child: const CacheProvider(
child: MyHomePage(title: 'GraphQL Widget'),
),
);
}
}
Animation that shows that cache doesn't work
So, the question is - what is the right way to implement cache and how check it works.
Thank you!
The examples are meant to be standalone - as such they use separate clients and caches. The consequence of this is that it is re-instantiated every mount. In other words, every time you navigates to the example's route, you get a new cache, so you can't see the caching effects. For a more substantial example where you can see if the cache is working, see the starwars example (related github discussion)

How can I render custom widget according to html tags using flutter_html package?

I have a HTML document and I want to render it with Flutter using flutter_html plugin. I want to render different typography differently. Eg. I want to have different font and size for bold and different for non-bold.
I tried reading the documentation which has a property for the Html constructor called customRenderer, I couldn't understand the implementation for it.
Below is the code from documentation.
Html(
data: """
<!--For a much more extensive example, look at example/main.dart-->
<div>
<h1>Demo Page</h1>
<p>This is a fantastic nonexistent product that you should buy!</p>
<h2>Pricing</h2>
<p>Lorem ipsum <b>dolor</b> sit amet.</p>
<h2>The Team</h2>
<p>There isn't <i>really</i> a team...</p>
<h2>Installation</h2>
<p>You <u>cannot</u> install a nonexistent product!</p>
<!--You can pretty much put any html in here!-->
</div>
""",
padding: EdgeInsets.all(8.0),
backgroundColor: Colors.white70,
defaultTextStyle: TextStyle(fontFamily: 'serif'),
linkStyle: const TextStyle(
color: Colors.redAccent,
),
onLinkTap: (url) {
},
customRender: (node, children) {
if(node is dom.Element) {
switch(node.localName) {
case "video": return Chewie(...);
case "custom_tag": return CustomWidget(...);
}
}
},
)
If I just can change font size and font family according to the tag name, it will do.
Here's a sample using flutter_html. (as of typing this you should go with flutter_html_all. Same package but there has been some renaming. customRender is now customRenders (plural))
return Html(
data: <span>Some normal HTML</span> then appears a <customtag>Some data in this one</customtag>,
tagsList: Html.tags..addAll(['customtag']),
customRenders:
{
customTagMatcher(): CustomRender.widget(widget: (context, buildChildren)
{
final element = context.tree.element!;
// Your conditions with the element.
// finally return your own custom widget:
return Container(child: Text('My custom widget...'));
}),
}
);
CustomRenderMatcher customTagMatcher() => (context) => context.tree.element?.localName == 'customtag';
More info:
https://github.com/Sub6Resources/flutter_html#customrenders
https://github.com/Sub6Resources/flutter_html/discussions/973
On mobile you can use webview_flutter to display html script on a page.
WebView(
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
final String contentBase64 = base64Encode(const Utf8Encoder().convert(Source.html));
webViewController.loadUrl('data:text/html;base64,$contentBase64');
},
),
If you're planning to use this on web, you can use dart:html
void main() {
// ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
'html-view-tag',
(int viewId) => IFrameElement()
..srcdoc = Source.html
..style.border = 'none');
runApp(const MyApp());
}
and on your Screen, add HtmlElementView like a Widget
body: Center(
child: HtmlElementView(viewType: 'html-view-tag')
),
I just defined the source html like this
class Source {
static const html =
'<!--For a much more extensive example, look at example/main.dart-->'
'<div>'
'<h1>Demo Page</h1>'
'<p>This is a fantastic nonexistent product that you should buy!</p>'
'<h2>Pricing</h2>'
'<p>Lorem ipsum <b>dolor</b> sit amet.</p>'
'<h2>The Team</h2>'
'<p>There isn\'t <i>really</i> a team...</p>'
'<h2>Installation</h2>'
'<p>You <u>cannot</u> install a nonexistent product!</p>'
'<!--You can pretty much put any html in here!-->'
'</div>';
}