I want to use to Google places api and
I am trying to call this api but I am getting this. error
Error: XMLHttpRequest error.
static Future<List<Result>?> searchPlaces(context, String query) async {
String mapApiKey = "API_KEY";
String _host = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
final url = '$_host?query=$query&key=$mapApiKey';
//
var response = await http.get(Uri.parse(url));
print(response.body);
//
if (response.statusCode == '200') {
GPlacesSearch result = GPlacesSearch.fromJson(jsonDecode(response.body));
return result.results!;
} else
return null;
}
}
I don't know which platform you are using, but I guess the solution would be to disable chrome web security.
If you are working on mac try the following steps
Go to flutter\bin\cache and remove a file named: flutter_tools.stamp
Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.
Find '--disable-extensions'
Add '--disable-web-security'
And if you are working on windows just search for how to disable web security for chrome
Use this url 'https://cors-anywhere.herokuapp.com' before your actual url e.g.
String baseUrl = 'https://cors-anywhere.herokuapp.com';
String actualUrl = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
String finalUrl = "$baseUrl/$actualUrl";
static Future<List<Result>?> searchPlaces(context, String query) async {
String mapApiKey = "YOUR_KEY_HERE";
var _sessionToken = Uuid().v4();
String _host =
'https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/textsearch/json';
final url = '$_host?query=$query&key=$mapApiKey';
//
var response = await http.get(Uri.parse(url);
//
GPlacesSearch result = GPlacesSearch.fromJson(jsonDecode(response.body));
return result.results!;
}
}
Related
I am using flutter to process a link and download it to the device using dio package.
But the problem is dart is replacing all '&' with '\u0026' and making the link unusable. is there a way to avoid this problem? Thanks in advance.
Here's the code:
const uuid = Uuid();
final Dio dio = Dio();
// * create random id for naming downloaded file
final String randid = uuid.v4();
// * create a local instance of state all media
List<MediaModel> allMedia = state.allMedia;
// * create an instance of IGDownloader utility class from ~/lib/utilities
final IGDownloader igd = IGDownloader();
// * make a download link from provided link from the GetNewMedia event
final link = await igd.getPost(event.link);
link.replaceAll('\u0026', '&');
print(await link);
Output:
// expected : "http://www.example.com/example&examples/"
// result: "http://www.example.com/example\u0026example"
Pass your url to cleanContent function and don't forget to add imports
import 'package:html/parser.dart';
import 'package:html_unescape/html_unescape.dart';
static String cleanContent(String content, {bool decodeComponent = false}) {
if (content.contains("<p>")) {
content = content.replaceAll("<p>", "").trim();
}
if (content.contains("</p>")) {
content = content.replaceAll("</p>", "").trim();
}
var unescape = HtmlUnescape();
content = unescape.convert(content).toString();
if (content.contains("\\<.*?\\>")) {
content = content.replaceAll("\\<.*?\\>", "").trim();
}
content = parseHtmlString(content,decodeComponent: decodeComponent);
return content;
}
static String parseHtmlString(String htmlString,{bool decodeComponent = false}) {
final document = parse(htmlString);
String parsedString = parse(document.body!.text).documentElement!.text;
if(parsedString.contains("%3A")){
parsedString = parsedString.replaceAll("%3A", ":");
}
if(parsedString.contains("%2F")){
parsedString = parsedString.replaceAll("%2F", "/");
}
if(decodeComponent){
parsedString = Uri.decodeComponent(parsedString);
}
return parsedString;
}
replaceAll returns the modified string, but leaves original String untouched.
Try:
print(await link.replaceAll('\u0026', '&'));
or
newLink = link.replaceAll('\u0026', '&');
print(await newLink);
this code is for fetching data from json api , there is just one error in the code , and this is the error :
error
class RemoteService {
Future<List<Adhan>?> getAdhan() async {
var client = http.Client();
var uri = Uri.parse("https://api.pray.zone/v2/times/today.json?city=paris");
var response = await client.get(uri);
if (response.statusCode == 200) {
var json = response.body;
return adhanFromJson(json);
}
}
}
I tried to search in the Internet and YouTube for any problem similar to my problem, I did not find anything to help me.
how can i fix this error ?
Your function named adhanFromJson probably returns a Adhan, while getAdhan expects you to return a List<Adhan> or null.
Either change the return type of getAdhan or return a List<Adhan>.
I am trying to send Form data to the backend using Flutter.
As a result, all the text type data is sent easily but my image file is not shared.
Help me Guys
uploadImage(
filepath,url) async {
EasyLoading.show(status: 'Uploading Data...');
try {
final result = await InternetAddress.lookup('example.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
var request = http.MultipartRequest('POST', Uri.parse(url));
print(filepath); *// this filepath is not empty*
request.files.add(await http.MultipartFile.fromPath('image', filepath));
request.headers.addAll(headers);
request.fields['name'] = _pName.text;
request.fields['store_id'] = store_id;
request.fields['seller_name'] = seller_name;
request.fields['seller_id'] = seller_id;
request.fields['product_id'] = 35.toString();
request.fields['stock_status_id'] = 6.toString();
request.fields['price'] = _pPrice.text;
request.fields['model'] = _pModel.text;
request.fields['sku'] = _pSKU.text;
request.fields['status'] = 1.toString();
request.fields['product_name'] = "Shoes Sport";
request.fields['is_approved'] = 1.toString();
request.fields['special'] = false.toString();
request.fields['quantity'] = _pQuantity.text;
var res = await request.send();
if(res.statusCode==200)
{
EasyLoading.showSuccess('Data is Uploaded!\n Waiting For Approval');
EasyLoading.dismiss();
print(res.reasonPhrase);
Navigator.pop(context);
}
print(request.fields);
// print(filepath);
}
}
on SocketException catch (_) {
EasyLoading.showError("Internet Connection is not available");
}
}
all the data is uploaded except image, i have also crosschecked the parameter its correct.
chek the spelling of "image" it should be same mention in your api doc and the one you are using, your code seems correct i was stuck at the same issue i was using the image key but the key was "profile " please do a recheck , let me know if this works
I have the following method which is use dto verify a ticket/token
var ticketArray = ticket.split('|');
//First check to verify token using simple versification algo
if (widget.eventID.toString() != (ticketArray[0])) {
setState(() {
ticketMainMsg = 'This QR code is NOT VALID';
ticketsubtitle = ticketArray.length != 2
? 'The QR code is fake'
: 'QR code could belong to another event';
ticketStatus = false;
return;
});
}
//Make API call
ticketModel = HttpVerifyTicketPost(
eventId: widget.eventID,
ticket: ticket,
scannerId: widget.scannerId,
).verifyTicket();
}
From above, you can see I do a very simple check on the qr code/token if this simple step fails, I don't bother making an API call and I set the state based on these values.
However if the check passes, then I proceed to make an API call to the server to fully verify the token/code.
My issue is I am struggling to now assign the values from the API call to the ticketStatus, ticketMainMsgand ticketsubtitle parameters. Can anyone helo shed some light. I am quite new to flutter but I am aware that the TicketModel will be a type of Future. My background is PHP so forgive me!
EDIT: The httpVerifyTicket Class
class HttpVerifyTicketPost {
String ticket;
int someId;
int anotherId;
HttpVerifyTicketPost(
{required this.ticket, required this.someId, required this.anotherId});
String verifyURL =
'https://api.com/api/vendors/scanner/native/verify/ticket';
Future<TicketModel> verifyTicket() async {
var storage = await SharedPreferences.getInstance();
var code= storage.getString('code');
var client = http.Client();
var ticketModel = null;
var body = {
'ticket': ticket,
'scanner': scannerCode,
'someId': someId,
'anotherId': anotherId
};
try {
var url = Uri.parse(verifyURL);
var res = await client.post(url, body: jsonEncode(body));
if (res.statusCode == 200) {
var jsonString = res.body;
var jsonMap = json.decode(jsonString);
ticketModel = TicketModel.fromJson(jsonMap);
}
return ticketModel;
} catch (Exception) {
return ticketModel;
}
}
}
Try this please
HttpVerifyTicketPost(
eventId: widget.eventID,
ticket: ticket,
scannerId: widget.scannerId,
).verifyTicket().then((value){setState(() {
ticketModel=value
});
});
I don't quite understand what you want to achieve, but maybe you need to add an asynchronous method like
ticketModel = await HttpVerifyTicketPost( //add await eventId: widget.eventID, ticket: ticket, scannerId: widget.scannerId, ).verifyTicket();
and you must add async like Future Foo() async {your code...}
It Work When String is used BUT Can't fetch String Object.
it Works :-
String? url = "https://api.thedogapi.com/v1/images/search";
var raw = await http.get(Uri.parse(url));
it is Not working :-
getInfoFromSharedPref() async {
dogApiLink = await SharedPreferenceHelper().getDogName();
}
var raw = await http.get(Uri.parse('${dogApiLink}'));
where dogApiLink is String and having Link But Not working.
bro it's direct .. I just don't understand if the return from the shared preferences that you are taking is a link ???? if it's only dog name then that's your problem.. if it's a legitimate link then
{
String uri = "The link";
var response = await http.get(Uri.parse(uri), "The headers of the api").then(){
// The task you wanna perform.
}
}