Post and get data using flutter webview - flutter

I'm having a problem with Flutter. More precisely, since it is not a language that I have a command of, I did something by looking at the videos. Of course, old videos etc. I've been in trouble.
First of all, I will write what I want to do and what I failed to achieve. I am pulling my website into application with webview. There is no problem here. Then I added onesignal. This also works flawlessly. But I want to get the id called playerid that onesignal defines for each device and post it to my php page. I tried many plugins for this, but I could not succeed. Then I sent it as a cookie, it still didn't work. I realized that I can send data as get in the latest webview link, but the fact that I can't pull the variable I created here also infuriated me. I'm adding the codes below and asking for help from an expert friend. If there is, you can suggest an easy way to POST and GET. Thanks everyone in advance.
In the code below, I can't get the variable that I defined as userid and printed in the link section. In the simplest way, if I do this, it can work for now.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:dio/dio.dart';
void main() async {
runApp(PnlbaseApp());
}
class PnlbaseApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'PNLBASE APP',
home: PnlbaseAppPage(),
);
}
}
class PnlbaseAppPage extends StatefulWidget {
PnlbaseAppPage({Key? key}) : super(key: key);
#override
_PnlbaseAppPageState createState() => _PnlbaseAppPageState();
}
class _PnlbaseAppPageState extends State<PnlbaseAppPage> {
#override
void initState() {
super.initState();
OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);
OneSignal.shared.setAppId("APP-ID");
OneSignal.shared.promptUserForPushNotificationPermission().then((accepted) {
print("Accepted permission: $accepted");
});
OneSignal.shared.getDeviceState().then((deviceState) {
print("OneSignal: device state: ${deviceState?.jsonRepresentation()}");
var userid;
userid = deviceState?.userId;
print(userid);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
top: true,
child: WebView(
initialUrl: "https://app.pnlbase.com/login?playerid",
javascriptMode: JavascriptMode.unrestricted,
),
),
);
}
}

Related

Flutter scrape Google Shopping

I am trying to get a product price by searching for the product in Google Shopping with a given title and storeName.
I found this question on SO, which explains how you would do it with Python. How can something like this be done with Flutter?
Also like I said, is there any way to select the store?
I couldn't find anything on this. Any help is appreciated. Let me know if you need any more info!
I tried it like this:
Future<void> getGoogleShoppingResult() async {
const String requestUrl =
'https://www.google.com/search?q=minecraft+toys&tbm=shop';
final response = await http.get(Uri.parse(requestUrl));
dom.Document document = parser.parse(response.body);
final elements = document.querySelectorAll(
'div.sh-np__product-title.translate-content',
);
print(elements.first.innerHtml);
}
With this I tried to get the title of the first found product. But this never finds any product, even though I copied the selector from Google Shopping.
You should use these packages:
webview_flutter
http
html
And wait till JavaScript has been loaded.
This tutorial can help:
https://www.youtube.com/watch?v=EHk66k___EY
The code snippet:
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:html/dom.dart' as dom;
class WebViewPageExample extends StatefulWidget {
const WebViewPageExample({Key? key}) : super(key: key);
#override
State<WebViewPageExample> createState() => _WebViewPageExampleState();
}
class _WebViewPageExampleState extends State<WebViewPageExample> {
late WebViewController _controller;
#override
Widget build(BuildContext context) {
return WebView(
onWebViewCreated: _onWebViewCreated,
javascriptMode: JavascriptMode.unrestricted,
initialUrl: "https://www.google.com/search?q=minecraft+toys&tbm=shop",
onPageFinished: _onPageFinished,
);
}
void _onWebViewCreated(WebViewController controller) {
_controller = controller;
}
Future _onPageFinished(String url) async {
final html = await _controller.runJavascriptReturningResult(
"new XMLSerializer().serializeToString(document);");
final div = dom.Document.html(html)
.querySelectorAll('div.sh-np__product-title.translate-content');
log('Count: ${div.length}');
}
}

Getx Controller not fetching data

So i have an implementation where i pass the id of a parent category and it fetches its child category from the database and displays them in another screen (view).
When i click on the parent, it sends the its category ID to the screen whose code is below and the it suppose to get the data from the database to be used in the screen. However, it says null when you click from the previous page to this new screen. If you directly do a hot reload, the data gets displayed.
Does it mean the below code doesn't get run when the screen is first loaded?
Note that all controllers and repositories have been set in the dependecies class and initialised in the main.
var childCatItem =
Get.find<ChildCategoriesController>().getChildCategory(childCatId);
Parent Category Screen Function to Pass ID.
The below code gets the ID from the already loaded data.
onTapLeftService: (){
int childCatId = randomController.isLoaded ? randomController.randomServicesList[0].children[0].id : 0;
Get.toNamed(RouteHelper.getChildCategoryServicesPage(childCatId));
},
The below code is the route where it is gotten and passed to the screen
//This is the route implementation. This is called in the above code.
static String getChildCategoryServicesPage(int childCatId) =>
'$childCategoryServicesPage?childCatId=$childCatId';
GetPage(
name: childCategoryServicesPage,
page: () {
var childCatId = Get.parameters['childCatId'];
return ChildCategoryServicesScreen(
childCatId: int.parse(childCatId!));
},
transition: Transition.fadeIn),
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:personal_start/controller/nonemergency_services/child_categories_controller.dart';
import 'package:personal_start/helper/app_styles.dart';
import 'package:personal_start/widget/title_text.dart';
class ChildCategoryServicesScreen extends StatelessWidget {
int childCatId; //Here I receive the ID of the parent category into this screen
ChildCategoryServicesScreen({Key? key, required this.childCatId})
: super(key: key);
#override
Widget build(BuildContext context) {
var childCatInstance = Get.find<ChildCategoriesController>(); // I create an instance of the controller
var childCatItem =
Get.find<ChildCategoriesController>().getChildCategory(childCatId); //Here I make an API call to the database, passing the parent category ID.
print(childCatItem);
print(childCatInstance.childCategory!.title); //I receive a null value here.
return Scaffold(
appBar: AppBar(
title: TitleTextWidget(titleText: 'Child Cat Title'),
leading: GestureDetector(
onTap: () {
Get.back();
},
child: const Icon(Icons.arrow_back_outlined),
),
backgroundColor: AppStyles.appPrimaryColor,
),
// body: !childCatItem.isLoaded
// ? const CustomLoader()
// : Center(child: TitleTextWidget(titleText: 'It has Loaded')),
);
}
}
you can pass data using getx argument
https://www.kindacode.com/article/using-getx-get-for-navigation-and-routing-in-flutter/
Try this way
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:personal_start/controller/nonemergency_services/child_categories_controller.dart';
import 'package:personal_start/helper/app_styles.dart';
import 'package:personal_start/widget/title_text.dart';
class ChildCategoryServicesScreen extends GetView<ChildCategoriesController> {
ChildCategoryServicesScreen({Key? key}): super(key: key);
#override
ChildCategoriesController controller = Get.put(ChildCategoriesController());
#override
Widget build(BuildContext context) {
...//TODO: YOUR CODE HERE
}
ChildCategoriesController
class ChildCategoriesController extends GetxController {
late int childCatId;
...//TODO: YOUR CODE HERE
#override
void onInit() {
int childCatId = Get.arguments[0];
...//TODO: YOUR CODE HERE
super.onInit();
}
#override
void onClose() {}
...//TODO: YOUR CODE HERE
}

How to generate Pre Launch report for Flutter App?

I have a login screen which uses phone authentication for creating account.
I have used Firebase Phone auth for login and also have stored one number for testing purpose.
But don't know how to pass the number and OTP to generate Pre Launch Report.
They are asking for Username, Username Resource ID, Password , Password Resource ID.
Where to find Resource ID for username and password fields in flutter code.
In the Google play console at the bottom of the left
Click on App content
Click on App access
Click on manage
Click on add new instructions
Add your all details here it should be test accounts
Try this :
dependencies:
flutter_runtime_env: ^0.0.4
Example:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_runtime_env/flutter_runtime_env.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _isInFirebaseTestLab = false;
#override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
var result = await inFirebaseTestLab();
setState(() {
_isInFirebaseTestLab = result;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('is in FirebaseTest Lab'),
),
body: Center(
child: Text('is in FirebaseTest Lab: $_isInFirebaseTestLab\n'),
),
),
);
}
}

How to open a PDF file in a Flutter App and have a selectable view?

I want to implement a App in Flutter that allows the user to view PDF-files and select and copy the text thereinin so that I can proceed using the copied text from the Clipboard.
To be more precise I want want my Code to be somewhat like the following but with a package that allows to copy from the displayed PDF file.
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:pdf_viewer_plugin/pdf_viewer_plugin.dart';
import 'package:flutter/services.dart';
class PDFPage extends StatefulWidget {
final File file;
final Function onPressed;
const PDFPage(this.file,this.onPressed);
#override
_PDFPageState createState() => _PDFPageState();
}
class _PDFPageState extends State<PDFPage> {
#override
void initState() {
Clipboard.setData(ClipboardData(text: ''));
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: PdfViewer(
filePath: widget.file.path,
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.beach_access),
onPressed: ()async{
ClipboardData data = await Clipboard.getData('text/plain');
widget.onPressed(data);
},
),
);
}
}
The package I am using here is
pdf_viewer_plugin: ^1.0.0+2
That seems not to work. It does display the PDF file but I can't select text or copy from it. I have also tried
flutter_full_pdf_viewer: ^1.0.6
advance_pdf_viewer: ^1.1.6
and some more I can't remind the name of.
Is there a package that allows me to do so, or a modest way to either modify or create such a package?
Thanks a lot.

Flutter, WebView - rebuild with custom HTML

I want to show some generated HTML in a WebView in my Flutter App.
The StatefulWidget which contains the WebView can change certain properties upon which the WebView would have to rebuild.
TL;DR: How to supply custom HTML without initialUrl?
Up to now I used the initialUrl propety of the WebView constructor to supply an URI with my HTML directly embedded:
WebView(
initialUrl: Uri.dataFromString(myHtml, mimeType: 'text/html').toString(),
)
Now I realized, I must rebuild the WebView with different values when some states get set. (Namely a dropdown above the WebView). As the name tells, this URI is just initial.
So my question is: How can I update the HTML in the WebView? Is there maybe some way to reset the internal state of the WebView?
I guess webview's api doesn't allow to do that, but you can use a workaround: just save the HTML to temp file and provide an URI to WebView using initialUrl. Here's the example:
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:webview_flutter/webview_flutter.dart';
class HomePage extends StatefulWidget {
#override
State<StatefulWidget> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Uri uri;
Future<void> _showHtml(String html) async {
final tempDir = await getTemporaryDirectory();
final path = join(tempDir.path, 'page.html');
final tempFile = File(path);
tempFile.writeAsStringSync(html);
setState(() {
uri = Uri(scheme: 'file', path: path);
});
}
#override
void initState() {
super.initState();
_showHtml('<html>Test</html>');
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: SafeArea(
child: uri != null ? WebView(
initialUrl: uri.toString(),
) : Container()
),
);
}
}
You can also use onWebViewCreated callback to save webview's controller and use the controller later to load other using loadUrl method.