Displaying an iframe in Dart - dart

Is it possible to display an iframe in Dart?
Below is the code that I am using
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final wordPair = WordPair.random();
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('Welcome to Flutter'),
),
body: Center(
child: Text(wordPair.asPascalCase), // With this highlighted text.
),
),
);
}
}
I am not sure how to add an iframe into this. Below is the snippet that is given in the documentation
factory IFrameElement() => JS(
'returns:IFrameElement;creates:IFrameElement;new:true',
'#.createElement(#)',
document,
"iframe");

I agree that using webview_flutter plugin shows HTML in Flutter. But, this plugin is currently supported in mobile but not yet for web. Here is an example of how you implement this on mobile:
Sample code using webview_flutter plugin:
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final Completer<WebViewController> _controller =
Completer<WebViewController>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: WebView(
initialUrl: 'https://flutter.dev/',
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
javascriptMode: JavascriptMode.unrestricted,
),
);
}
}
Actual Output:
And regarding your question how to implement IFrameElement. There is actually an existing blog where it provides all the steps to understand this. But as mentioned, this is still in beta.
After I followed all the necessary steps, I've ended up in this example:
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
import 'dart:html';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: IframeDemo(),
),
),
);
}
}
class IframeDemo extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return MyWidget();
}
}
class MyWidget extends State<IframeDemo> {
String _url;
IFrameElement _iframeElement;
#override
initState() {
super.initState();
_url = 'https://flutter.dev/';
_iframeElement = IFrameElement()
..src = _url
..id = 'iframe'
..style.border = 'none';
//ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
'iframeElement',
(int viewId) => _iframeElement,
);
}
#override
Widget build(BuildContext context) {
print('url is $_url');
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
),
SizedBox(
height: 600,
width: 600,
child: HtmlElementView(
viewType: 'iframeElement',
),
),
],
);
}
}
Sample Output:

Related

How to add a splashscreen to a Flutter webview app?

**Hi guys, how can I add a splashscreen to this webview Flutter app.
Because I would like to upload it to App Store.
I uploaded this code to google Store and it has been accepted.
I am very new to flutter and dont have an experince, so please rewrite the code you would tell me to be sure that the answered code is working.
Thank you in advance.
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'My Website',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(
title: 'My Website',
url: 'https://www.???.com/'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title, this.url});
final String title;
final String url;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
WebViewController _controller;
final Completer<WebViewController> _controllerCompleter =
Completer<WebViewController>();
//Make sure this function return Future<bool> otherwise you will get an error
Future<bool> _onWillPop(BuildContext context) async {
if (await _controller.canGoBack()) {
_controller.goBack();
return Future.value(false);
} else {
return Future.value(true);
}
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () => _onWillPop(context),
child: Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SafeArea(
child: WebView(
key: UniqueKey(),
onWebViewCreated: (WebViewController webViewController) {
_controllerCompleter.future.then((value) => _controller = value);
_controllerCompleter.complete(webViewController);
},
javascriptMode: JavascriptMode.unrestricted,
initialUrl: widget.url,
)),
),
);
}
}
you can create a widget that displays a splash screen and hold the widget for some seconds then push it to your new widget, like this:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'My Website',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(
title: 'My Website',
url: 'https://www.google.com/',
),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title, this.url});
final String title;
final String url;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool loading = true;
WebViewController _controller;
final Completer<WebViewController> _controllerCompleter =
Completer<WebViewController>();
//Make sure this function return Future<bool> otherwise you will get an error
Future<bool> _onWillPop(BuildContext context) async {
if (await _controller.canGoBack()) {
_controller.goBack();
return Future.value(false);
} else {
return Future.value(true);
}
}
startSplashScreen() async {
var duration = const Duration(seconds: 3);
return Timer(
duration,
() {
setState(() {
loading = false;
});
},
);
}
#override
void initState() {
super.initState();
startSplashScreen();
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () => _onWillPop(context),
child: Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: loading == true
? Center(
child: Text(
'APP LOGO',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
)
: SafeArea(
child: WebView(
key: UniqueKey(),
initialUrl: widget.url,
onWebViewCreated: (WebViewController webViewController) {
_controllerCompleter.complete(webViewController);
},
javascriptMode: JavascriptMode.unrestricted,
),
),
),
);
}
}
result:
use this package
Add this code before navigating to your homescreen
new SplashScreen(
seconds: 14,
navigateAfterSeconds: HomeScreen(),
title: Text('Welcome In SplashScreen'),
image: Image.asset('splash.png'),
backgroundColor: Colors.white,
photoSize: 100.0,
loaderColor: Colors.red
);
EDIT for example:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'My Website',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SplashScreen(
seconds: 5,
navigateAfterSeconds: MyHomePage(
title: 'My Website',
url: 'https://www.???.com/'),
title: Text('Welcome In SplashScreen'),
backgroundColor: Colors.white,
loaderColor: Colors.red
),
);
}
}

Why expanded view is not being shown

I am trying out flutter, here I am having a simple card view, where there is an add AddButton , when the button is pressed new card is being added.
Now, i wanted to have it scrollable so added ListView and an expanded Widget in the Column. Here is the code...
import 'package:flutter/material.dart';
import './products.dart';
import './product_control.dart';
class ProductManger extends StatefulWidget {
final String startingProduct;
ProductManger({this.startingProduct = "Sweet Tester"});
#override
State<StatefulWidget> createState() {
return _ProductManagerState();
}
}
class _ProductManagerState extends State<ProductManger> {
List<String> _products = ['Food Tester'];
#override
void initState() {
_products.add(widget.startingProduct);
super.initState();
}
void _addProducts(String product) {
setState(() {
_products.add(product);
});
}
#override
Widget build(BuildContext context) {
return Column(children: [
Container(margin: EdgeInsets.all(10.0), child: ProductControl(_addProducts)),
Expanded(child: Products(_products))
]);
}
}
If I change that Expanded to Container with height, it works as expected, but now, nothing is being displayed except a button.
I am currently following a tutorial, exact same code is written, however, version of flutter is 0.3.2 and i am using 1.5
Or there could be some issue with the emulator?
Hope this helps.
Here is the listView code
import 'package:flutter/material.dart';
class Products extends StatelessWidget {
final List<String> products;
Products([this.products = const []]);
#override
Widget build(BuildContext context) {
return ListView(
children: products
.map((element) => Card(
child: Column(
children: <Widget>[
Image.asset('assets/food.jpg'),
Text(element)
],
),
))
.toList());
}
}
This is what is visible when i use Container with height 300.0 insted to expand
And when i use expand, this is what being shown
Please try to change
#override
Widget build(BuildContext context) {
return Column(children: [
Container(margin: EdgeInsets.all(10.0), child: ProductControl(_addProducts)),
Expanded(child: Products(_products))
]);
}
To
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column: children: [
Container(
margin: EdgeInsets.all(10.0),
child: ProductControl(_addProducts)),
Expanded(child: Products(_products))
]);
}
If it does not work , Please give a look to SingleChildeScrollView
Ok, so after hours of time I found out finally, the error was in my main.dart file.
Initially, the code was
import 'package:flutter/material.dart';
import './product_manager.dart';
import 'package:flutter/rendering.dart';
void main(){
debugPaintSizeEnabled=true;
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.deepOrange,
accentColor: Colors.deepPurple
),
home: Scaffold(
appBar: AppBar(
title: Text("Alpit anand"),
),
body: Column(
children: [ProductManger()],
)),
);
}
}
But when i changed to
import 'package:flutter/material.dart';
import './product_manager.dart';
import 'package:flutter/rendering.dart';
void main(){
debugPaintSizeEnabled=true;
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.deepOrange,
accentColor: Colors.deepPurple
),
home: Scaffold(
appBar: AppBar(
title: Text("Alpit anand"),
),
body:
ProductManger(),
),
);
}
}
Thanks to pskink, you really helped me out. Thanks for your time. Although I still have to find out, why it wasn't working that way.

How to remove null text on the screen in flutter

I build an app in which there are two pages(screens),the first page receives the data from second page.But the problem is that before getting the data from second page it is showing "null" on the first page screen.Below are the codes of these two pages.Note:The first page screen is the main launcher screen.
First Page
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
String value;
MyHomePage({Key key,this.value}):super(key:key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Flutter"),
),
body:Center(
child:new Text("${widget.value}") )
}
Second Page
class _List extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyList(),
);
}
}
class MyList extends StatefulWidget {
#override
_MyListState createState() => _MyListState();
}
class _MyListState extends State<MyList> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text("List"),
),
body: new Container(
padding: new EdgeInsets.only(left: 5.0,top: 20.0,right: 5.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
GestureDetector(
onTap: (){
var route=new MaterialPageRoute(builder: (BuildContext context)=>new MyHomePage(value: "Apple",),
);
Navigator.of(context).push(route);
},
child: new Card(
child:
new Column(
children: <Widget>[
new Text('Apple'),
new Text('Banana')
],
),
),
),
);
}
}
You can use a blank Container() widget instead of Text() widget like the code below :
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Flutter"),
),
body:Center(
child: widget.value==null ? Container() : new Text("${widget.value}")
)
);
}
}

Flutter, calling FutureBuilder from a raised button's onPressed doesn't call the builder property

I'm trying to learn Dart/Flutter and am working on an example where there's a button on the app that says "Get Data", and when I touch it I want to retrieve JSON data from a restful service.
I see the web service being called in fetchPost, but the builder property of the FutureBuilder isn't called.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'ResultsList.dart';
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Restul Test',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: (){
FutureBuilder<ResultsList>(
future: fetchPost(),
builder: (context, snapshot){
print('In Builder');
}
);
},
child: Text('Get data'),
)
],
),
)
);
}
}
Future<ResultsList> fetchPost() async {
final response = await http.get('http://mywebserviceurl');
if (response.statusCode == 200){
print('Received data');
return ResultsList.fromJson(json.decode(response.body));
}
else {
throw Exception('Failed to load data');
}
}
Interestingly though, if I move the FutureBuilder out of the onPressed of the button to the child of Center, I do see the builder property getting called.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'ResultsList.dart';
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Restul Test',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: FutureBuilder<ResultsList>(
future: fetchPost(),
builder: (context, snapshot){
print ('In Builder');
return Container();
}
)
)
);
}
}
Future<ResultsList> fetchPost() async {
final response = await http.get('http://mywebserviceurl');
if (response.statusCode == 200){
print('Received data');
return ResultsList.fromJson(json.decode(response.body));
}
else {
throw Exception('Failed to load data');
}
}
Obviously I'm missing something, but any idea what I'm doing wrong?
If you want to get some data from request - you don't need FutureBuilder. You can do:
RaisedButton(
onPressed: (){
fetchPost().then((result) {
print('In Builder');
})
},
child: Text('Get data'),
)
or
RaisedButton(
onPressed: () async {
var result = await fetchPost()
print('In Builder');
},
child: Text('Get data'),
)
The onPressed method in this RaisedButton is actually not doing anything. It just creates a new FutureBuilder which does nothing but existing^^ It's like you would just call 1+1;, which just creates a value, but that value is not used to do anything.
RaisedButton(
onPressed: (){
FutureBuilder<ResultsList>(
future: fetchPost(),
builder: (context, snapshot){
print('In Builder');
}
);
},
child: Text('Get data'),
)
You could have body be assigned to a Widget(which could just be called body or whatever you want^^), which you then change in a setState((){body = FutureBuilder(/*...*/}); call.
For me FutureBuilder not working in onPresses...
I used this way :
I defined a variable in state:
bool visiblity = false;
and I used this code in build:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () {
visiblity=true;
fetchPost();
},
child: Text('Get data'),
),
FutureBuilder<ResultsList>(
future: ("Your View Model that return from call back"),
builder: (context, snapshot) {
if (visiblity) {
print('In Builder');
visiblity=false;
} else
return Container();
}
),
],
),
)
);
}
I didn't put FutureBuilder in onPressed. I put that in body and changed visibility after return result.

Material app in Column with regular sized navigation bar

I want to display an Image on top of my entire app. So I Placed an image and my dashboard in a column in Main.dart file
My main.dart file.
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
body: new SafeArea(
child: Column(
children: <Widget>[
new Image.asset('assets/ads.png'),
new Expanded(
child: Dashboard(),
)
],
),
),
),
);
}
}
and Dashboard.dart
import 'package:flutter/material.dart';
class Dashboard extends StatefulWidget {
#override
_DashboardState createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new Scaffold(
appBar: new AppBar(title: new Text('Books')),
body: new Container(
child: new Center(
child: new Text('data'),
),
),
),
);
}
}
Now, this code generates output like this.
I need regular sized Appar. This AppBar is really big. Can someone suggest what's wrong here?
Do Like This :-
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return new MaterialApp(
debugShowCheckedModeBanner: false,
home: new Scaffold(
body: new SafeArea(
child: Column(
children: <Widget>[
new Image.network("https://via.placeholder.com/350x100"),
new Expanded(
child: Dashboard(),
)
],
),
),
),
);
}
}
class Dashboard extends StatefulWidget {
#override
_DashboardState createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text('Books')),
body: new Container(
child: new Center(
child: new Text('data'),
),
),
);
}
}

Resources