flutter_inappwebview - How to update URL? - flutter

I would like to know how I can update my URL with the flutter_inappwebview package.
Here is my code:
InAppWebView(
initialData: InAppWebViewInitialData(
data: videoName,
),
The videoName variable is updated using setState. However, InAppWebView does not display the new URL.
How can I update videoName using setState?

You have 2 page :1) videopage 2)webviewpage
video page so :
From the video page pass the url with parameter in webviewpage .
Example:
In Video View Page :
Navigator.of(context).push(MaterialPageRoute -> (builder)=> WevViewPage(url);
In web view Page :
WebViewPage extents stateless ...
String url;
WebViewPage(this.url);
//here is the constructor
now show
InAppWebView(
initialData: InAppWebViewInitialData(
data: url,
),

Related

How to add back button to WebView in Flutter to dismiss the WebView altogether?

Currently when I tap on an image, it should open a web view as the image object has an associated url. I am using the url_launcher library for Flutter, and I have implemented the code as follows:
onTap: () async {
final url = image.url;
if (await canLaunch(url)) {
await launch(
url,
forceSafariVC: true,
forceWebView: true,
enableJavaScript: true,
);
}
},
My understanding is that this launches a WebView, which is an in-app browser rather than taking the user out of the app and into a separate browser app. This works fine, but the page loads much slower and Javascript elements do not work properly (e.g. animated text on websites). On the other hand,
onTap: () async {
final url = banners[index].url;
if (await canLaunch(url)) {
await launch(
url
);
}
},
works much better as it is faster and everything loads in properly, but it opens an external browser, which is not what I want.
Another issue is that I would like to add a Done button on the top left corner of the WebView to completely exit the WebView and return to where I was in the app. I only have a back button on the bottom left (on the Android emulator), that lets me go to the previous page I was at in the browser.
How do I customise the layout of the WebView, if I do not have any access to it? The url_launcher seems to handle the WebView creation internally, so I'm wondering how can I gain access from the above code to add that button?
Thank you!
If you use the native webview in this manner then you can't customise the ui. But instead, since you are displaying image you can use image.network from flutter.
Image.network(imgURL,fit: BoxFit.fill,
loadingBuilder:(BuildContext context, Widget child,ImageChunkEvent loadingProgress) {
if (loadingProgress == null)
return child;
return Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null ?
loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes
: null,
),
);
},
),
Or, you can also use official webview plugin from flutter team to create in app web view.
webview_flutter: ^2.3.1
In this approaches if you add a back button in ui you can the use Navigator.pop(context); on onPressed property in button to go back

Flutter webpage navigation

How to get following result in flutter web app using Getx package
On tapping the container in intiating screen, I wish to pass parameters in following fashion ( 2 variable parameters and 1 fixed parameter i.e. product) which should open webpage with following url
https://myapp.local/variableParameter1/variableParameter2/product
Above link should be without # and also when user opens above link, should lead to (ProductScreen) with 2 parameters being passed as arguments
My code is structured in following fashion and works well on mobile devices.
Part of intiating screen
GestureDetector(
child: Container(
//some content inside
),
onTap: () {
Get.toNamed(
'/product/$variableParameter1/$variableParameter2',
);
},
)
Part of main.dart file
GetPage(
name: '/productscreen/variableparameter1/variableparameter1',
page: () => ProductScreen(),
binding: ProductScreenBinding(),
),
Part of controllers for ProductScreen
class ProductController extends GetxController {
var screenprm1 =Get.arguments[0].toString().obs;
var screenprm2 =Get.arguments[1].toString().obs;
}

Flutter web URL navigation like http://localhost:60117/ItemDetails?pId=1 not working

In my flutter project, i have to share a URL which is directly redirect to a particular product details page through social media . so i have added routing-information using velocity_x, my main.dart page is as follows
#override
Widget build(BuildContext context) {
return MaterialApp.router(
debugShowCheckedModeBanner: false,
title: 'AppName',
theme: ThemeData(
primaryColor: MyAppTheme.primaryColor,
accentColor:MyAppTheme.accentColor
),
routeInformationParser: VxInformationParser(),
routerDelegate: VxNavigator(routes: {
"/": (_,__)=> MaterialPage(child:SplashScreen()),
"/login": (_,__)=> MaterialPage(child:SignUp()),
"/home": (_,__)=> MaterialPage(child:Home(selectedIndex: 0)),
"/ItemDetails": (uri, _){
final pId=int.parse(uri.queryParameters["pId"]);
return MaterialPage(
child:ItemDetailsFromAdd(
pId:pId.toString() ,
));
},
}),
)
My Initial route is splash screen and after checking authentication it redirects to login page or home page. when i click on a particular item, creates a url "http://localhost:60117/ItemDetails?pId=1" this. But when i try to launch this url from another tab, first it load product detail page and suddenly redirects to my initial page splashscreen.
I tried to change "/" initial route from "/" to "/splash" and changed my "<base href="/splash/">" but it gives a page not found error initially.
How can i access my product detail page directly using this "http://localhost:60117/ItemDetails?pId=1" URL in correct way.
onGenerateRoute: (settings) {
List<String> pathComponents = settings.name.split('/');
if (pathComponents[1] == 'invoice') {
return MaterialPageRoute(
builder: (context) {
return Invoice(arguments: pathComponents.last);
},
);
} else
return MaterialPageRoute(
builder: (context) {
return LandingPage();
},
);
;
},
Try this way
Try adding a hashtag # to the URL:
http://localhost:60117/#/ItemDetails?pId=1
It's the only way to share it if you are running a progressive web app. What's the left of the /#/ tells the browser from where to get the app, and what's after it is the router logic. If you try to remove the /#/, the app doesn't behave normally and reverts back to the default route.
After long testing i found the answer, here my initial route ('/') redirect to the'SplashScreen'. so when i try to access particular item using URL first it comes to SplashScreen and there i coded to redirect to home or Login based on the user authentication. so when i access to a particular item using url it redirect to my login/home. the solution is i changed my initial route to Home page.

Upload in background on Flutter

What’s the best way to upload data in the background, but don’t cancel this upload when the user switches screens? I would also like to show Snackbar when the upload finishes (even if I'm on a different screen already).
On Android, I’ve been using Service + BroadcastReceiver or WorkManager. I Can’t find the way of doing it in Flutter.
You can use package https://pub.dev/packages/flutter_uploader
This plugin is based on WorkManager in Android and NSURLSessionUploadTask in iOS to run upload task in background mode.
Create new upload task:
final uploader = FlutterUploader();
final taskId = await uploader.enqueue(
url: "your upload link", //required: url to upload to
files: [FileItem(filename: filename, savedDir: savedDir, fieldname:"file")], // required: list of files that you want to upload
method: UploadMethod.POST, // HTTP method (POST or PUT or PATCH)
headers: {"apikey": "api_123456", "userkey": "userkey_123456"},
data: {"name": "john"}, // any data you want to send in upload request
showNotification: false, // send local notification (android only) for upload status
tag: "upload 1"); // unique tag for upload task
);
Listen for upload progress
final subscription = uploader.progress.listen((progress) {
//... code to handle progress
});
For Snackbar , you can use ScaffoldMessenger to make Snackbar persist across routes https://flutter.dev/docs/release/breaking-changes/scaffold-messenger
The ScaffoldMessenger now handles SnackBars in order to persist across routes and always be displayed on the current Scaffold. By default, a root ScaffoldMessenger is included in the MaterialApp
The ScaffoldMessenger creates a scope in which all descendant Scaffolds register to receive SnackBars, which is how they persist across these transitions. When using the root ScaffoldMessenger provided by the MaterialApp
code snippet
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('snack'),
duration: const Duration(seconds: 1),
action: SnackBarAction(
label: 'ACTION',
onPressed: () { },
),
));
You can use this dart package workmanager

flutter:I can't load image through plugin webview_flutter

I wanna load HTML string through plugin webview_flutter, I try it like those:
But I couldn't load an image in my HTML string, meanwhile, I made WebView as a child for SizedBox, its height and width were adapted to device screen. Even though, it still exceeded device's width. I check the official demo, but it was futile
return WebView(
initialUrl: '',
onWebViewCreated: (controller) async {
String content = base64Encode(Utf8Encoder().convert(html));
controller.loadUrl('data:text/html;base64,$content');
},
);