Not able to view web page in webview on Android emulator - android

I am trying to run the WebView Sample of Flutter in android emulator which is provided by Android studio itself. Now the problem I am facing is while I am running the sample I am not able to view the web page in WebView itself.
When the app runs for the first time it asks me to open the initialUrl into either into the chrome or web browser see below screenshots.
However, when I run the same sample in my mobile device it works fine and I can see the web page insdie WebView
Code
class _WikipediaExplorerState extends State<WikipediaExplorer> {
Completer<WebViewController> _controller = Completer<WebViewController>();
final Set<String> _favorites = Set<String>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Wikipedia Explorer'),
// This drop down menu demonstrates that Flutter widgets can be shown over the web view.
actions: <Widget>[
NavigationControls(_controller.future),
Menu(_controller.future, () => _favorites),
],
),
body: WebView(
initialUrl: 'https://en.wikipedia.org/wiki/Kraken',
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
),
floatingActionButton: _bookmarkButton(),
);
}
_bookmarkButton() {
return FutureBuilder<WebViewController>(
future: _controller.future,
builder:
(BuildContext context, AsyncSnapshot<WebViewController> controller) {
if (controller.hasData) {
return FloatingActionButton(
onPressed: () async {
var url = await controller.data.currentUrl();
_favorites.add(url);
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Saved $url for later reading.')),
);
},
child: Icon(Icons.favorite),
);
}
return Container();
},
);
}
}

Related

flutter webview plugin display as high resolution

I am attempting to create a android application to be installed on a android TV device i manage to display it using flutter_webview plugin, but all of the image are blurry and not displayed as its resolution. Any workaround with this problem?
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: Builder(builder: (BuildContext context) {
return const WebView(
initialUrl: "https://apple.com",
javascriptMode: JavascriptMode.unrestricted,
);
}),
);
}

How to open a link in a in-app browser window in flutter and how to change browser window header

I would like to know how to open links in an in-app browser, just like this:enter image description here
You can achieve this using flutter_webview plugin.
Example code:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter WebView example'),
// This drop down menu demonstrates that Flutter widgets can be shown over the web view.
actions: <Widget>[
NavigationControls(_controller.future),
SampleMenu(_controller.future),
],
),
// We're using a Builder here so we have a context that is below the Scaffold
// to allow calling Scaffold.of(context) so we can show a snackbar.
body: Builder(builder: (BuildContext context) {
return WebView(
initialUrl: 'https://flutter.dev',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
onProgress: (int progress) {
print("WebView is loading (progress : $progress%)");
},
javascriptChannels: <JavascriptChannel>{
_toasterJavascriptChannel(context),
},
navigationDelegate: (NavigationRequest request) {
if (request.url.startsWith('https://www.youtube.com/')) {
print('blocking navigation to $request}');
return NavigationDecision.prevent;
}
print('allowing navigation to $request');
return NavigationDecision.navigate;
},
onPageStarted: (String url) {
print('Page started loading: $url');
},
onPageFinished: (String url) {
print('Page finished loading: $url');
},
gestureNavigationEnabled: true,
);
}),
floatingActionButton: favoriteButton(),
);
}

Open Flutter Application Using Dynamic Links [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm building a flutter application, and am having some trouble actually opening the app using the firebase_dynamic_links package. I basically took the example code found at https://pub.dev/packages/firebase_dynamic_links#-example-tab- in order to get started, but changed the information in their example to match my own firebase project (which has been setup in both android and iOS, but this testing has all been done with iOS).
I will include code and more useful information below, but I was really just hoping to get a simplified example of how this process should work. I have searched online quite a bit, following different tutorials, but none of them have done the trick for me. It could just be that I'm quite new to flutter, and am missing basic things. In my final application, I will be using dynamic links to allow users to invite other users to join the app (as well as groups within the app) via text, just to give context as to why it is needed.
Here is the code for what I have so far, but as I mentioned it is largely based off of the example from the link above.
main.dart
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:firebase_dynamic_links/firebase_dynamic_links.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:shopsync/helloworld.dart';
void main() async {
//Setup firebase connection
WidgetsFlutterBinding.ensureInitialized();
final FirebaseApp app = await FirebaseApp.configure(
name: 'shop-sync-d97d8',
options: Platform.isIOS
? const FirebaseOptions(
googleAppID: 'my_googleAppID',
gcmSenderID: 'my_senderID',
databaseURL: 'https://shop-sync-d97d8.firebaseio.com',
apiKey: 'AIzaSyC1TdwTs_KRXMGG2oIAGMX8v48HWqS62dc',
)
: const FirebaseOptions(
googleAppID: 'my_googleAppID',
apiKey: 'myApiKey',
databaseURL: 'my_url',
),
);
runApp(MaterialApp(
title: 'Dynamic Links Example',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => _MainScreen(),
'/helloworld': (BuildContext context) => HelloWorldScreen(),
},
));
}
class _MainScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() => _MainScreenState();
}
class _MainScreenState extends State<_MainScreen> {
String _linkMessage;
bool _isCreatingLink = false;
String _testString =
"To test: long press link and then copy and click from a non-browser "
"app. Make sure this isn't being tested on iOS simulator and iOS xcode "
"is properly setup. Look at firebase_dynamic_links/README.md for more "
"details.";
#override
void initState() {
super.initState();
initDynamicLinks();
}
void initDynamicLinks() async {
final PendingDynamicLinkData data =
await FirebaseDynamicLinks.instance.getInitialLink();
final Uri deepLink = data?.link;
if (deepLink != null) {
Navigator.pushNamed(context, deepLink.path);
}
FirebaseDynamicLinks.instance.onLink(
onSuccess: (PendingDynamicLinkData dynamicLink) async {
final Uri deepLink = dynamicLink?.link;
if (deepLink != null) {
Navigator.pushNamed(context, deepLink.path);
}
}, onError: (OnLinkErrorException e) async {
print('onLinkError');
print(e.message);
});
}
Future<void> _createDynamicLink(bool short) async {
setState(() {
_isCreatingLink = true;
});
final DynamicLinkParameters parameters = DynamicLinkParameters(
uriPrefix: "https://shopsync.page.link",
link: Uri.parse("https://shopsync.page.link/helloworld"),
androidParameters: AndroidParameters(
packageName: 'com.chrismcdonnell.shopsync',
minimumVersion: 0,
),
dynamicLinkParametersOptions: DynamicLinkParametersOptions(
shortDynamicLinkPathLength: ShortDynamicLinkPathLength.short,
),
iosParameters: IosParameters(
bundleId: 'com.chrismcdonnell.shopsync',
minimumVersion: '0',
),
);
Uri url;
if (short) {
final ShortDynamicLink shortLink = await parameters.buildShortLink();
url = shortLink.shortUrl;
} else {
url = await parameters.buildUrl();
}
setState(() {
_linkMessage = url.toString();
_isCreatingLink = false;
});
}
#override
Widget build(BuildContext context) {
return Material(
child: Scaffold(
appBar: AppBar(
title: const Text('Dynamic Links Example'),
),
body: Builder(builder: (BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ButtonBar(
alignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: !_isCreatingLink
? () => _createDynamicLink(false)
: null,
child: const Text('Get Long Link'),
),
RaisedButton(
onPressed: !_isCreatingLink
? () => _createDynamicLink(true)
: null,
child: const Text('Get Short Link'),
),
],
),
InkWell(
child: Text(
_linkMessage ?? '',
style: const TextStyle(color: Colors.blue),
),
onTap: () async {
if (_linkMessage != null) {
await launch(_linkMessage);
}
},
onLongPress: () {
Clipboard.setData(ClipboardData(text: _linkMessage));
Scaffold.of(context).showSnackBar(
const SnackBar(content: Text('Copied Link!')),
);
},
),
Text(_linkMessage == null ? '' : _testString)
],
),
);
}),
),
);
}
}
class _DynamicLinkScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Material(
child: Scaffold(
appBar: AppBar(
title: const Text('Hello World DeepLink'),
),
body: const Center(
child: Text('Hello, World!'),
),
),
);
}
}
helloworld.dart
//IMPORT NEEDED PACKAGES
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
//CREATE STATEFUL WIDGET
class HelloWorldScreen extends StatefulWidget {
#override
_HelloWorldScreen createState() => _HelloWorldScreen();
}
//CREATE STATE WIDGET
class _HelloWorldScreen extends State<HelloWorldScreen> {
#override
Widget build(BuildContext context) {
//Since this class represents an entire screen, return a scaffold with elements inside it
return Scaffold(
backgroundColor: Colors.white,
//Create AppBar w/ title "My Account"
appBar: AppBar(
title: Text('Hello World'),
automaticallyImplyLeading: false,
),
//Most of the content of the screen will go here
body: SafeArea(
child: Text('Testing'),
),
);
}
}
And lastly, here is the dynamic link I created within the console for testing. Although the final version of the application will create them programatically.
If anything else is needed please let me know. Any help would be greatly appreciated.

Flutter save the time to a variable when a user accessed a tab

Im new to flutter so please bear with me. So I have a simple webview app with 2 tabs
I just wanna ask if how can I save the user load time to a variable name lastloaded in time format then when the user re-enters that tab, a function will check the lastloaded variable if its greater than 1 minute and perform a refresh.
I honestly dont know what to search for this problem. Please assist. Thank you!
if you want to see an example code here:
class _CategoriesPageState extends State<CategoriesPage> {
WebViewController _myController;
final Completer<WebViewController> _controller =
Completer<WebViewController>();
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: WebView(
initialUrl: 'www.facebook.com',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (controller) {
_controller.complete(controller);
},
onPageFinished: (controller) async {
(await _controller.future).evaluateJavascript("document.getElementsByClassName('footer-container')[0].style.display='none';");
(await _controller.future).evaluateJavascript("document.getElementById('st_notification_1').style.display='none';");
(await _controller.future).evaluateJavascript("document.getElementById('sidebar_box').style.display='none';");
},
),
floatingActionButton: FutureBuilder<WebViewController>(
future: _controller.future,
builder: (BuildContext context, AsyncSnapshot<WebViewController> controller) {
if (controller.hasData) {
return FloatingActionButton(
onPressed: () {
controller.data.reload();
},
child: Icon(Icons.refresh),
);
}
return Container();
}
),
),
);
}
}
For getting the date and time, User DateTime class. Use this class and use the function difference to get the difference between DateTimes.
var lastLoaded;
void tappingOnTab(){
final now = DateTime.now();
if(lastLoaded != null){
if(now.difference(lastLoaded).inMinutes > 1){
// yes last loaded time is more than 1 min ago
}
}
lastLoaded = now;
}
If you want to persist the last loaded time over multiple app instances, use SharedPreferences: https://pub.dev/packages/shared_preferences.

Is there WebView in Flutter? [duplicate]

This question already has answers here:
How to add a Webview in Flutter?
(10 answers)
Closed 2 years ago.
I am looking for WebView in flutter. How can I show my Html contents in flutter ?
Actually our books format is Html so I need WebView or a way to parse Html in flutter programming.
A Flutter plugin that provides a webview widget is available now for Developers Preview
usage
return Scaffold(
appBar: AppBar(
title: const Text('Flutter WebView example'),
),
body: const WebView(
initialUrl: 'https://flutter.io',
javaScriptMode: JavaScriptMode.unrestricted,
),
);
full code
You can use
> flutter_webview_plugin
It is a plugin that allow Flutter to communicate with a native WebView.
Note: The webview is not integrated in the widget tree, it is a native view on top of the flutter view. you won't be able to use snackbars, dialogs ...
You can use my plugin flutter_inappwebview, which is a Flutter Plugin that allows you to add inline webviews integrated with the widget tree or open an in-app browser window! It offers a lot of events, methods, and options compared to other webview plugins!
Main Classes:
InAppWebView: Flutter Widget for adding an inline native WebView integrated into the flutter widget tree. To use InAppWebView class on iOS you need to opt-in for the embedded views preview by adding a boolean property to the app's Info.plist file, with the key io.flutter.embedded_views_preview and the value YES.
ContextMenu: This class represents the WebView context menu.
HeadlessInAppWebView: Class that represents a WebView in headless mode. It can be used to run a WebView in background without attaching an InAppWebView to the widget tree.
InAppBrowser: In-App Browser using native WebView.
ChromeSafariBrowser: In-App Browser using Chrome Custom Tabs on Android / SFSafariViewController on iOS.
InAppLocalhostServer: This class allows you to create a simple server on http://localhost:[port]/. The default port value is 8080.
CookieManager: This class implements a singleton object (shared instance) which manages the cookies used by WebView instances.
HttpAuthCredentialDatabase: This class implements a singleton object (shared instance) which manages the shared HTTP auth credentials cache.
WebStorageManager: This class implements a singleton object (shared instance) which manages the web storage used by WebView instances.
Quick example:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
InAppWebViewController webView;
String url = "";
double progress = 0;
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('InAppWebView Example'),
),
body: Container(
child: Column(children: <Widget>[
Container(
padding: EdgeInsets.all(20.0),
child: Text(
"CURRENT URL\n${(url.length > 50) ? url.substring(0, 50) + "..." : url}"),
),
Container(
padding: EdgeInsets.all(10.0),
child: progress < 1.0
? LinearProgressIndicator(value: progress)
: Container()),
Expanded(
child: Container(
margin: const EdgeInsets.all(10.0),
decoration:
BoxDecoration(border: Border.all(color: Colors.blueAccent)),
child: InAppWebView(
initialUrl: "https://flutter.dev/",
initialHeaders: {},
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
debuggingEnabled: true,
)
),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onLoadStart: (InAppWebViewController controller, String url) {
setState(() {
this.url = url;
});
},
onLoadStop: (InAppWebViewController controller, String url) async {
setState(() {
this.url = url;
});
},
onProgressChanged: (InAppWebViewController controller, int progress) {
setState(() {
this.progress = progress / 100;
});
},
),
),
),
ButtonBar(
alignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Icon(Icons.arrow_back),
onPressed: () {
if (webView != null) {
webView.goBack();
}
},
),
RaisedButton(
child: Icon(Icons.arrow_forward),
onPressed: () {
if (webView != null) {
webView.goForward();
}
},
),
RaisedButton(
child: Icon(Icons.refresh),
onPressed: () {
if (webView != null) {
webView.reload();
}
},
),
],
),
])),
),
);
}
}
Screenshot:
If you just want to show a static html content, you can try this package: flutter_html_view. Flutter just supports a full-screen webview, an inline webview has not been supported yet.

Categories

Resources